# Metodi e oggetti forniti da QOwnNotes

# Avvio di un programma esterno in background

# Chiamata al metodo e parametri

/**
 * Wrapper QML per avviare un processo separato
 *
 * @param executablePath the path of the executable
 * @param parameters a list of parameter strings
 * @param callbackIdentifier an identifier to be used in the onDetachedProcessCallback() function (optional)
 * @param callbackParameter an additional parameter for loops or the like (optional)
 * @param processData data written to the process if the callback is used (optional)
 * @param workingDirectory the working directory to execute the process in (optional, only works without callback)
 * @return true on success, false otherwise
 */
bool startDetachedProcess(QString executablePath, QStringList parameters,
                            QString callbackIdentifier, QVariant callbackParameter,
                            QByteArray processData, QString workingDirectory);
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# Esempio

Esempio semplice:

script.startDetachedProcess("/path/to/my/program", ["my parameter"]);
1

Esecuzione di molti processi:

for (var i = 0; i < 100; i++) {
    var dur = Math.floor(Math.random() * 10) + 1;
    script.startDetachedProcess("sleep", [`${dur}s`], "my-callback", i);
}

function onDetachedProcessCallback(callbackIdentifier, resultSet, cmd, thread) {
    if (callbackIdentifier == "my-callback") {
        script.log(`#${thread[1]} i[${thread[0]}] t${cmd[1]}`);
    }
}
1
2
3
4
5
6
7
8
9
10

You may want to take a look at the example custom-actions.qml (opens new window), callback.qml (opens new window) or execute-command-after-note-update.qml (opens new window).

Potresti anche voler dare un'occhiata all'hook onDetachedProcessCallback.

# Avvio di un programma esterno e attesa dell'output

# Chiamata al metodo e parametri

/**
 * Wrapper QML per avviare un processo sincrono
 *
 * @param executablePath the path of the executable
 * @param parameters a list of parameter strings
 * @param data the data that will be written to the process (optional)
 * @param workingDirectory the working directory to execute the process in (optional)
 * @return the text that was returned by the process
QByteArray startSynchronousProcess(QString executablePath, QStringList parameters, QByteArray data, QString workingDirectory);
1
2
3
4
5
6
7
8
9

# Esempio

var result = script.startSynchronousProcess("/path/to/my/program", ["my parameter"], "data", "/path/to/execute/in");
1

You may want to take a look at the example encryption-keybase.qml (opens new window).

# Ottenere il percorso della cartella della nota corrente

# Chiamata al metodo e parametri

/**
 * Wrapper QML per ottenere il percorso della cartella della nota corrente
 *
 * @return il percorso della cartella della nota corrente
 */
QString currentNoteFolderPath();
1
2
3
4
5
6

# Esempio

var path = script.currentNoteFolderPath();
1

You may want to take a look at the example absolute-media-links.qml (opens new window).

# Ottenere la nota corrente

# Chiamata al metodo e parametri

/**
 * Wrapper QML per ottenere la nota corrente
 *
 * @returns {NoteApi} the current note object
 */
NoteApi currentNote();
1
2
3
4
5
6

# Esempio

var note = script.currentNote();
1

You may want to take a look at the example custom-actions.qml (opens new window).

# Accesso al widget di registro

# Chiamata al metodo e parametri

/**
 * Wrapper QML per accedere al registro
 *
 * @param text
 */
void log(QString text);
1
2
3
4
5
6

# Esempio

script.log("my text");
1

# Download di un URL in una stringa

# Chiamata al metodo e parametri

/**
 * Wrapper QML per scaricare un url e ritornarlo come testo
 *
 * @param url
 * @return {QString} il contenuto del url  scaricato
 */
QString downloadUrlToString(QUrl url);
1
2
3
4
5
6
7

# Esempio

var html = script.downloadUrlToString("https://www.qownnotes.org");
1

You may want to take a look at the example insert-headline-with-link-from-github-url.qml (opens new window).

# Download di un URL nella cartella multimediale

# Chiamata al metodo e parametri

/**
  * Wrapper QML per scaricare un URL nella cartella multimediale e restituire il supporto
  * url o il testo dell'immagine di markdown del supporto relativo alla nota corrente
  *
  * URL @param {QString}
  * @param {bool} returnUrlOnly if true solo l'URL multimediale verrà restituito (valore predefinito false)
  * @return {QString} il markdown multimediale o l'URL
 */
QString downloadUrlToMedia(QUrl url, bool returnUrlOnly);
1
2
3
4
5
6
7
8
9

# Esempio

var markdown = script.downloadUrlToMedia("http://latex.codecogs.com/gif.latex?\frac{1}{1+sin(x)}");
1

You may want to take a look at the example paste-latex-image.qml (opens new window).

# Inserimento di un file multimediale nella cartella multimediale

# Chiamata al metodo e parametri

/**
  * QML wrapper per inserire un file multimediale nella cartella multimediale e tornare
  * l'URL del supporto o il testo dell'immagine di markdown del supporto relativo alla nota corrente
  *
  * @param {QString} mediaFilePath
  * @param {bool} returnUrlOnly se true solo l'URL multimediale verrà restituito (valore predefinito false)
  * @return {QString} il markdown multimediale o l'URL
1
2
3
4
5
6
7

# Esempio

var markdown = script.insertMediaFile("/percorso/del/tuo/file.png");
1

You may want to take a look at the example scribble.qml (opens new window).

# Inserimento di un file allegato nella cartella allegati

# Chiamata al metodo e parametri

 * Wrapper QML per inserire un file allegato nella cartella
 * `attachments`e restituire l'URL dell'allegato o il testo markdown
 * dell'allegato relativi alla nota corrente
 *
 * @param {QString} attachmentFilePath
 * @param {QString} nome del file da usare nel markdown
 * @param {bool} returnUrlOnly se true sarà ritornato solo l'URL
 *                             dell'allegato (default false)
 * @return {QString} il markdown dell'allegato o l'URL
 */
QString ScriptingService::insertAttachmentFile(const QString &attachmentFilePath,
                                               const QString &fileName,
                                               bool returnUrlOnly);
1
2
3
4
5
6
7
8
9
10
11
12
13

# Esempio

var markdown = script.insertAttachmentFile("/percorso/del/tuo/file.png");
1

# Rigenerazione dell'anteprima della nota

Aggiorna l'anteprima della nota.

# Chiamata al metodo e parametri

/**
 * Rigenera l'anteprima della nota
 */
QString ScriptingService::regenerateNotePreview();
1
2
3
4

# Esempio

script.regenerateNotePreview();
1

You may want to take a look at the example scribble.qml (opens new window).

# Registrazione di un'azione personalizzata

# Chiamata al metodo e parametri

/ **
  * Registra un'azione personalizzata
  *
  * @param identifier l'identificatore dell'azione
  * @param menu Inserisce il testo mostrato nel menu
  * @param button Inserisce il testo mostrato nel pulsante
  * (nessun pulsante verrà visualizzato se vuoto)
  * @param icon il percorso del file dell'icona o il nome di un'icona del tema freedesktop
  * troverai un elenco di icone qui:
  * https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
  * @param useInNoteEditContextMenu se true usa l'azione nella modifica della nota
  * menu contestuale (predefinito: falso)
  * @param hideButtonInToolbar se true il pulsante non verrà mostrato nel file
  * barra degli strumenti delle azioni personalizzate (impostazione predefinita: false)
  * @param useInNoteListContextMenu se true usa l'azione nell'elenco delle note
  * menu contestuale (predefinito: false)
  */
void ScriptingService :: registerCustomAction (identificatore QString,
                                            QString menuText,
                                            QString buttonText,
                                            QString icon,
                                            bool useInNoteEditContextMenu,
                                            bool hideButtonInToolbar,
                                            bool useInNoteListContextMenu);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

TIP

Puoi anche assegnare scorciatoie locali e globali alle tue azioni personalizzate nelle Impostazioni dei collegamenti.

WARNING

Ricorda che le icone a tema freedesktop (opens new window) sono principalmente disponibili solo in Linux. Quindi se vuoi davvero usare un'icona in macOS o Windows, devi fornirne una col tuo script. Per fare in modo che il tuo script definisca un percorso corretto per la tua icona puoi usare la proprietà scriptDir.

# Esempio

importa QtQml 2.0
import QOwnNotesTypes 1.0

Script {
     /**
      * Inizializza le azioni personalizzate
      */
     funzione init() {
         // aggiungi un'azione personalizzata senza un pulsante
        script.registerCustomAction("mycustomaction1", "Menu text");

         // aggiungi un'azione personalizzata con un pulsante
        script.registerCustomAction("mycustomaction2", "Menu text", "Button text");

         // aggiungi un'azione personalizzata con un pulsante e l'icona del tema freedesktop
        script.registerCustomAction("mycustomaction3", "Menu text", "Button text", "task-new");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

For some more examples please see custom-actions.qml (opens new window).

TIP

Puoi anche attivare un'azione personalizzata dopo che l'applicazione è stata avviata con il parametro --action customAction_<identifier>. Per maggiori informazioni dai un'occhiata a Attiva le azioni del menu dopo l'avvio.

# Registrazione di un'etichetta

# Chiamata al metodo e parametri

/**
  * Registra un'etichetta su cui scrivere
  *
  * @param identifier l'identificatore dell'etichetta
  * @param text il testo mostrato nell'etichetta (opzionale)
 */
void ScriptingService::registerLabel(QString identifier, QString text);
1
2
3
4
5
6
7

# Esempio

script.registerLabel("html-label", "<strong>Strong</strong> HTML text<br />with three lines<br />and a <a href='https://www.qownnotes.org'>link to a website</a>.");

script.registerLabel("etichetta lunga", "un altro testo molto lungo, un altro testo molto lungo, un altro testo molto lungo, un altro testo molto lungo, un altro testo molto lungo, un altro testo molto lungo, un altro testo molto lungo, un altro testo molto lungo , un altro testo molto lungo, un altro testo molto lungo, un altro testo molto lungo che andrà a capo");

script.registerLabel("counter-label");
1
2
3
4
5

The labels will be visible in the Scripting panel, which you need to enable in the Window / Panels menu.

È possibile utilizzare sia testo normale che html nelle etichette. Il testo sarà selezionabile e sarà possibile fare clic sui collegamenti.

You may then want to take a look at the example script scripting-label-demo.qml (opens new window).

# Impostazione del testo di un'etichetta registrata

# Chiamata al metodo e parametri

/**
  * Imposta il testo di un'etichetta registrata
  *
  * @param identifier l'identificatore dell'etichetta
  * @param text il testo mostrato nell'etichetta
 */
void ScriptingService::setLabelText(QString identifier, QString text);
1
2
3
4
5
6
7

# Esempio

script.setLabelText("counter-label", "counter text");
1

È possibile utilizzare sia testo normale che html nelle etichette. Il testo sarà selezionabile e sarà possibile fare clic sui collegamenti.

You may then want to take a look at the example script scripting-label-demo.qml (opens new window).

# Creazione di una nuova nota

# Chiamata al metodo e parametri

/**
 * Crea una nuova nota
 *
 * @param text the note text
 */
void ScriptingService::createNote(QString text);
1
2
3
4
5
6

# Esempio

script.createNote("My note headline\n===\n\nMy text");
1

You may want to take a look at the example custom-actions.qml (opens new window).

TIP

If you turned off that your note headline determines the note filename then you have to rename your note file yourself afterward, like this:

var note = script.currentNote();
note.renameNoteFile('your-filename');
1
2

# Accesso agli appunti

# Chiamata al metodo e parametri

/**
 * Restituisce il contenuto degli appunti come testo o html
 *
 * @param asHtml returns the clipboard content as html instead of text
 */
QString ScriptingService::clipboard(bool asHtml);
1
2
3
4
5
6

# Esempio

var clipboardText = script.clipboard();
var clipboardHtml = script.clipboard(true);
1
2

You may want to take a look at the example custom-actions.qml (opens new window).

# Scrivi il testo nella finestra di modifica del testo della nota

# Chiamata al metodo e parametri

/**
 * Scrive il testo nella posizione corrente del cursore nella modifica del testo della nota
 *
 * @param text
 */
void ScriptingService::noteTextEditWrite(QString text);
1
2
3
4
5
6

# Esempio

// scrive il testo nella finestra di modifica del testo della nota
script.noteTextEditWrite("My custom text");
1
2

You might want to look at the custom action transformTextRot13 in the example custom-actions.qml (opens new window).

Puoi usarlo insieme a noteTextEditSelectAll per sovrascrivere l'intero testo della nota corrente.

# Leggi il testo selezionato nella finestra di modifica del testo della nota

# Chiamata al metodo e parametri

/**
  * Legge il testo selezionato nella finestra di modifica del testo della nota
 *
 * @return
 */
QString ScriptingService::noteTextEditSelectedText();

1
2
3
4
5
6
7

# Esempio

// legge il testo selezionato nella finestra di modifica del testo della nota
var text = script.noteTextEditSelectedText();
1
2

You might want to look at the custom action transformTextRot13 in the example custom-actions.qml (opens new window).

# Seleziona tutto il testo nella finestra di modifica del testo della nota

# Chiamata al metodo e parametri

/**
 * Seleziona tutto il testo nella finestra di modifica del testo della nota
 */
void ScriptingService::noteTextEditSelectAll();
1
2
3
4

# Esempio

script.noteTextEditSelectAll();
1

Puoi usarlo insieme a noteTextEditWrite per sovrascrivere l'intero testo della nota corrente.

# Seleziona la riga corrente nella finestra di modifica del testo della nota

# Chiamata al metodo e parametri

/**
  * Seleziona la riga corrente nella finestra di modifica del testo della nota
  */
void ScriptingService::noteTextEditSelectCurrentLine();
1
2
3
4

# Esempio

script.noteTextEditSelectCurrentLine();
1

# Seleziona la parola corrente nella finestra di modifica del testo della nota

# Chiamata al metodo e parametri

/**
 * Seleziona la parola corrente nella modifica del testo della nota
 */
void ScriptingService::noteTextEditSelectCurrentWord();
1
2
3
4

# Esempio

script.noteTextEditSelectCurrentWord();
1

# Imposta il testo attualmente selezionato nella finestra di modifica del testo della nota

# Chiamata al metodo e parametri

/**
 * Imposta il testo attualmente selezionato nella modifica del testo della nota
 *
 * @param start
 * @param end
 */
void ScriptingService::noteTextEditSetSelection(int start, int end);
1
2
3
4
5
6
7

# Esempio

// expands the current selection by one character
script.noteTextEditSetSelection(
    script.noteTextEditSelectionStart() - 1,
    script.noteTextEditSelectionEnd() + 1);
1
2
3
4

# Ottieni la posizione iniziale della selezione corrente nella finestra di modifica del testo della nota

# Chiamata al metodo e parametri

/**
 * Restituisce la posizione iniziale della selezione corrente nella modifica del testo della nota
 */
int ScriptingService::noteTextEditSelectionStart();
1
2
3
4

# Esempio

script.log(script.noteTextEditSelectionStart());
1

# Ottieni la posizione finale della selezione corrente nella finestra di modifica del testo della nota

# Chiamata al metodo e parametri

/**
 * Restituisce la posizione finale della selezione corrente nella modifica del testo della nota
 */
int ScriptingService::noteTextEditSelectionEnd();
1
2
3
4

# Esempio

script.log(script.noteTextEditSelectionEnd());
1

# Impostare il cursore del testo nella finestra di modifica del testo della nota su una determinata posizione

# Chiamata al metodo e parametri

/**
 * Imposta il cursore del testo nella modifica del testo della nota su una determinata posizione
  * 0 sarebbe l'inizio della nota
  * caso speciale: -1 sarebbe la fine della nota
 *
 * @param position
 */
void ScriptingService::noteTextEditSetCursorPosition(int position);
1
2
3
4
5
6
7
8

# Esempio

// salta all'undicesimo carattere nella nota
script.noteTextEditSetCursorPosition(10);

// salta alla fine della nota
script.noteTextEditSetCursorPosition(-1);
1
2
3
4
5

# Ottieni la posizione corrente del cursore del testo nella finestra di modifica del testo della nota

# Chiamata al metodo e parametri

/**
  * Restituisce la posizione corrente del cursore del testo nella finestra di modifica del testo della nota
  * 0 sarebbe l'inizio della nota
  */
int ScriptingService::noteTextEditCursorPosition();
1
2
3
4
5

# Esempio

script.log(script.noteTextEditCursorPosition());
1

# Leggi la parola corrente dalla finestra di modifica del testo della nota

# Chiamata al metodo e parametri

/**
 * Legge la parola corrente nella modifica del testo della nota
 *
 * @param withPreviousCharacters also get more characters at the beginning
 *                               to get characters like "@" that are not
 *                               word-characters
 * @return
 */
QString ScriptingService::noteTextEditCurrentWord(bool withPreviousCharacters);
1
2
3
4
5
6
7
8
9

# Esempio

// legge la parola corrente dalla finestra di modifica del testo della nota
var text = script.noteTextEditCurrentWord();
1
2

You may want to take a look at the example autocompletion.qml (opens new window).

# Controlla se la piattaforma è Linux, OS X o Windows

# Chiamata al metodo e parametri

bool ScriptingService::platformIsLinux();
bool ScriptingService::platformIsOSX();
bool ScriptingService::platformIsWindows();
1
2
3

# Esempio

if (script.platformIsLinux()) {
    // Verrà eseguito solo se sotto Linux
}
1
2
3

# Etichetta la nota corrente

# Chiamata al metodo e parametri

/**
  * Contrassegna la nota corrente con un'entichetta denominata tagName
  *
  * @param tagName
  */
void ScriptingService::tagCurrentNote(QString tagName);
1
2
3
4
5
6

# Esempio

// aggiungi un'etichetta "preferito" alla nota corrente
script.tagCurrentNote("preferito");
1
2

You might want to look at the custom action favoriteNote in the example favorite-note.qml (opens new window).

# Crea o recupera un'etichetta dal una lista di elementi

# Chiamata al metodo e parametri

/**
 * Recupera o crea un'etichetta tramite la lista dei suoi nomi
 * L'elemento nameList[0] è il più alto nella gerarchia (con parentId:
 * 0)
 *
 * @param nameList
 * @param createMissing {bool} se true (default) tutte le etichette
 *                             mancanti vengono create
 * @return TagApi oggetto associateo all'etichetta alla massima
 *                profondità
 */
TagApi *ScriptingService::getTagByNameBreadcrumbList(
    const QStringList &nameList, bool createMissing);
1
2
3
4
5
6
7
8
9
10
11
12
13

# Esempio

// crea tutti i tag fino al 3° livello e restituisce l'oggetto tag per
// tag "level3", which would look like that in the tag tree:
// level1 > level2 > level3
var tag = script.getTagByNameBreadcrumbList(["level1", "level2", "level3"]);
1
2
3
4

# Cerca le etichette per nome

# Chiamata al metodo e parametri

/**
 * Recupera tutti i tag eseguendo una ricerca di sottostringa nel campo del nome
 *
 * @param name {QString} name to search for
 * @return {QStringList} list of tag names
 */
QStringList ScriptingService::searchTagsByName(QString name);
1
2
3
4
5
6
7

# Esempio

// cerca tutti i tag che contengono il gioco di parole
var tags = script.searchTagsByName("game");
1
2

You may want to take a look at the example autocompletion.qml (opens new window).

# Cerca note in base al testo della nota

# Chiamata al metodo e parametri

/**
 * Restituisce un elenco di ID nota di tutte le note con un determinato testo nel testo della nota
 *
 * Sfortunatamente non esiste un modo semplice per utilizzare una QList<NoteApi*> in QML, quindi possiamo trasferire solo gli ID delle note
 *
 * @return {QList<int>} list of note ids
 */
QList<int> ScriptingService::fetchNoteIdsByNoteTextPart(QString text);
1
2
3
4
5
6
7
8

# Esempio

var noteIds = script.fetchNoteIdsByNoteTextPart("mytext");

noteIds.forEach(function (noteId){
    var note = script.fetchNoteById(noteId);

    // fare qualcosa con la nota
});
1
2
3
4
5
6
7

You may want to take a look at the example unique-note-id.qml (opens new window).

# Aggiungi un foglio di stile personalizzato

# Chiamata al metodo e parametri

/**
  * Aggiunge un foglio di stile personalizzato all'applicazione
 *
 * @param stylesheet
 */
void ScriptingService::addStyleSheet(QString stylesheet);
1
2
3
4
5
6

# Esempio

// ingrandisci il testo nell'elenco delle note
script.addStyleSheet("QTreeWidget#noteTreeWidget {font-size: 30px;}");
1
2

You may want to take a look at the example custom-stylesheet.qml (opens new window).

You can get the widget names from the *.ui files, for example the main window is mainwindow.ui (opens new window).

La documentazione Qt (ad esempio QMainWindow (opens new window)) può aiutarti a vedere come sono correlati tra loro i widget (cerca Eredita nelle pagine).

Il widget di base per quasi tutto è QWidget (opens new window). Quindi basta disegnare QWidget con, ad esempio, QWidget {background-color: black; color: white;} significherebbe che tutto ha un colore di sfondo nero e un colore di primo piano bianco.

TIP

The style.qss (opens new window) of qdarkstyle (opens new window) might also be a good reference for styles you can change.

Dai un'occhiata a Riferimento foglio di stile (opens new window) per un riferimento su quali stili sono disponibili.

Se vuoi inserire stili nell'anteprima HTML per modificare il modo in cui le note vengono visualizzate in anteprima, guarda notetomarkdownhtmlhook.

TIP

Se vuoi effettivamente vedere come appaiono le finestre di dialogo e quali sono i loro nomi, puoi scaricare Qt Creator (opens new window) e aprire i file *.ui al suo interno.

# Ricaricamento del motore di scripting

# Chiamata al metodo e parametri

/**
  * Ricarica il motore di scripting
 */
void ScriptingService::reloadScriptingEngine();
1
2
3
4

# Esempio

// ricaricare il motore di scripting
script.reloadScriptingEngine();
1
2

# Recupero di una nota in base al nome del file

# Chiamata al metodo e parametri

/**
 * Recupera una nota in base al nome del file
 *
 * @param fileName string the file name of the note (mandatory)
 * @param noteSubFolderId integer id of the note subfolder
 * @return NoteApi*
 */
NoteApi* ScriptingService::fetchNoteByFileName(QString fileName,
                                                int noteSubFolderId);
1
2
3
4
5
6
7
8
9

# Esempio

// recupera la nota in base al nome del file
script.fetchNoteByFileName("my note.md");
1
2

# Recupero di una nota dal suo ID

# Chiamata al metodo e parametri

/**
 * Recupera una nota in base al suo ID
 *
 * @param id int the id of the note
 * @return NoteApi*
 */
NoteApi* ScriptingService::fetchNoteById(int id);
1
2
3
4
5
6
7

# Esempio

// fetch note by id
script.fetchNoteById(243);
1
2

You may want to take a look at the example export-notes-as-one-html.qml (opens new window).

# Controllo dell'esistenza di una nota tramite il nome del file

# Chiamata al metodo e parametri

/**
 * Verifica se esiste un file di note in base al nome del file
 *
 * @param fileName string the file name of the note (mandatory)
 * @param ignoreNoteId ID intero di una nota da ignorare nell'assegno
 * @param noteSubFolderId ID intero della sottocartella della nota
 * @return bool
 */
bool ScriptingService::noteExistsByFileName(QString fileName,
                                            int ignoreNoteId,
                                            int noteSubFolderId);
1
2
3
4
5
6
7
8
9
10
11

# Esempio

// controlla se la nota esiste, ma ignora l'id di "note"
script.noteExistsByFileName("my note.md", note.id);
1
2

You may want to take a look at the example use-tag-names-in-filename.qml (opens new window).

# Copia del testo negli appunti

# Chiamata al metodo e parametri

/**
 * Copia il testo negli appunti come testo normale o dati mime html
 *
 * @param text string text to put into the clipboard
 * @param asHtml bool if true the text will be set as html mime data
 */
void ScriptingService::setClipboardText(QString text, bool asHtml);
1
2
3
4
5
6
7

# Esempio

// copia il testo negli appunti
script.setClipboardText("text to copy");
1
2

You may want to take a look at the example selected-markdown-to-bbcode.qml (opens new window).

# Andare a una nota

# Chiamata al metodo e parametri

/**
 * Sets the current note if the note is visible in the note list
 *
 * @param note NoteApi note to jump to
 * @param asTab bool if true the note will be opened in a new tab (if not already open)
 */
void ScriptingService::setCurrentNote(NoteApi *note, bool asTab = false);
1
2
3
4
5
6
7

# Esempio

// jump to the note
script.setCurrentNote(note);

// open note in new tab (if not already open)
script.setCurrentNote(note, true);
1
2
3
4
5

You may want to take a look at the example journal-entry.qml (opens new window).

# Passaggio a una sottocartella di note

# Chiamata al metodo e parametri

/**
 * Salta a una sottocartella di note
 *
 * @param noteSubFolderPath {QString} path of the subfolder, relative to the note folder
 * @param separator {QString} separator between parts of the path, default "/"
 * @return true if jump was successful
 */
bool ScriptingService::jumpToNoteSubFolder(const QString &noteSubFolderPath,
                                            QString separator);
1
2
3
4
5
6
7
8
9

# Esempio

// passa alla sottocartella delle note "una sottocartella"
script.jumpToNoteSubFolder("a sub folder");

// passa alla sottocartella delle note "sub" all'interno di "una sottocartella"
script.jumpToNoteSubFolder("a sub folder/sub");
1
2
3
4
5

TIP

È possibile creare una nuova sottocartella delle note nella sottocartella corrente chiamando mainWindow.createNewNoteSubFolder.

# Visualizzazione di una finestra di messaggio informativo

# Chiamata al metodo e parametri

/**
 * Mostra una finestra di messaggio informativo
 *
 * @param text
 * @param title (optional)
 */
void ScriptingService::informationMessageBox(QString text, QString title);
1
2
3
4
5
6
7

# Esempio

// mostrare una finestra di messaggio informativo
script.informationMessageBox("The text I want to show", "Some optional title");
1
2

# Visualizzazione di una finestra di messaggio interrogativo

# Chiamata al metodo e parametri

/**
 * Mostra una finestra di messaggio di domanda
 *
 * For information about buttons see:
 * https://doc.qt.io/qt-5/qmessagebox.html#StandardButton-enum
 *
 * @param text
 * @param title (optional)
 * @param buttons buttons that should be shown (optional)
 * @param defaultButton default button that will be selected (optional)
 * @return id of pressed button
 */
int ScriptingService::questionMessageBox(
        QString text, QString title, int buttons, int defaultButton);
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# Esempio

// mostra una finestra di messaggio con una domanda con un pulsante Applica e un pulsante di aiuto
// see: https://doc.qt.io/qt-5/qmessagebox.html#StandardButton-enum
var result = script.questionMessageBox(
    "The text I want to show", "Some optional title", 0x01000000|0x02000000, 0x02000000);
script.log(result);
1
2
3
4
5

Per informazioni sui pulsanti vedere StandardButton (opens new window).

You may also want to take a look at the example input-dialogs.qml (opens new window).

# Visualizzazione di una finestra di dialogo Apri file

# Chiamata al metodo e parametri

/**
 * Mostra una finestra di dialogo del file aperto
 *
 * @param caption (optional)
 * @param dir (optional)
 * @param filter (optional)
 * @return QString
 */
QString ScriptingService::getOpenFileName(QString caption, QString dir,
                                            QString filter);
1
2
3
4
5
6
7
8
9
10

# Esempio

// mostra una finestra di dialogo del file aperto
var fileName = script.getOpenFileName("Please select an image", "/home/user/images", "Images (*.png *.xpm *.jpg)");
1
2

# Visualizzazione di una finestra di dialogo Salva file

# Chiamata al metodo e parametri

/**
 * Mostra una finestra di dialogo di salvataggio del file
 *
 * @param caption (optional)
 * @param dir (optional)
 * @param filter (optional)
 * @return QString
 */
QString ScriptingService::getSaveFileName(QString caption, QString dir,
                                            QString filter);
1
2
3
4
5
6
7
8
9
10

# Esempio

// mostra una finestra di dialogo di salvataggio del file
var fileName = script.getSaveFileName("Please select HTML file to save", "output.html", "HTML (*.html)");
1
2

You may want to take a look at the example export-notes-as-one-html.qml (opens new window).

# Registrazione delle variabili delle impostazioni dello script

Si prega di impostare le variabili di settaggio nel proprio script e registrarle in una proprietà nominata settingsVariables.

L'utente può quindi impostare queste proprietà nelle impostazioni dello script.

# Esempio

// you have to define your registered variables so you can access them later
property string myString;
property bool myBoolean;
property string myText;
property int myInt;
property string myFile;
property string myDirectory;
property string mySelection;

// register your settings variables so the user can set them in the script settings
//
// unfortunately there is no QVariantHash in Qt, we only can use
// QVariantMap (that has no arbitrary ordering) or QVariantList (which at
// least can be ordered arbitrarily)
property variant settingsVariables: [
    {
        "identifier": "myString",
        "name": "I am a line edit",
        "description": "Please enter a valid string:",
        "type": "string",
        "default": "My default value",
    },
    {
        "identifier": "myBoolean",
        "name": "I am a checkbox",
        "description": "Some description",
        "text": "Check this checkbox",
        "type": "boolean",
        "default": true,
    },
    {
        "identifier": "myText",
        "name": "I am textbox",
        "description": "Please enter your text:",
        "type": "text",
        "default": "This can be a really long text\nwith multiple lines.",
    },
    {
        "identifier": "myInt",
        "name": "I am a number selector",
        "description": "Please enter a number:",
        "type": "integer",
        "default": 42,
    },
    {
        "identifier": "myFile",
        "name": "I am a file selector",
        "description": "Please select the file:",
        "type": "file",
        "default": "pandoc",
    },
    {
        "identifier": "myDirectory",
        "name": "I am a directory selector",
        "description": "Please select the directory:",
        "type": "directory",
        "default": "/home",
    },
    {
        "identifier": "mySelection",
        "name": "I am an item selector",
        "description": "Please select an item:",
        "type": "selection",
        "default": "option2",
        "items": {"option1": "Text for option 1", "option2": "Text for option 2", "option3": "Text for option 3"},
    }
];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

Inoltre puoi sovrascrivere settingsVariables con una funzione speciale registerSettingsVariables() come questa:

# Esempio

/**
  * Registra nuovamente le variabili delle impostazioni
  *
  * Utilizzare questo metodo se si desidera utilizzare il codice per sovrascrivere le variabili, ad esempio l'impostazione
  * valori predefiniti a seconda del sistema operativo.
 */
function registerSettingsVariables() {
    if (script.platformIsWindows()) {
        // override the myFile default value
        settingsVariables[3].default = "pandoc.exe"
    }
}
1
2
3
4
5
6
7
8
9
10
11
12

You may also want to take a look at the example variables.qml (opens new window).

# Memorizzazione e caricamento di variabili persistenti

# Chiamata al metodo e parametri

/**
  * Memorizza una variabile persistente
  * Queste variabili sono accessibili globalmente su tutti gli script
  * Utilizza un prefisso significativo nella tua chiave come "PersistentVariablesTest / myVar"
 *
 * @param key {QString}
 * @param value {QVariant}
 */
void ScriptingService::setPersistentVariable(const QString &key,
                                                const QVariant &value);


/ **
  * Carica una variabile persistente
  * Queste variabili sono accessibili globalmente su tutti gli script
  *
 * @param key {QString}
 * @param defaultValue {QVariant} valore di ritorno se l'impostazione non esiste (opzionale)
 * @return
 */
QVariant ScriptingService::getPersistentVariable(const QString &key,
                                                    const QVariant &defaultValue);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# Esempio

// memorizzare variabile persistente
script.setPersistentVariable("PersistentVariablesTest/myVar", result);

// caricare e registrare la variabile persistente
script.log(script.getPersistentVariable("PersistentVariablesTest/myVar", "nothing here yet"));
1
2
3
4
5

Assicurati di utilizzare un prefisso significativo nella tua chiave come PersistentVariablesTest/myVar perché le variabili sono accessibili da tutti gli script.

You may also want to take a look at the example persistent-variables.qml (opens new window).

# Caricamento delle variabili delle impostazioni dell'applicazione

# Chiamata al metodo e parametri

/**
 * Carica una variabile delle impostazioni dell'applicazione
 *
 * @param key {QString}
 * @param defaultValue {QVariant} return value if the setting doesn't exist (optional)
 * @return
 */
QVariant ScriptingService::getApplicationSettingsVariable(const QString &key,
                                                            const QVariant &defaultValue);
1
2
3
4
5
6
7
8
9

# Esempio

// caricare e registrare una variabile delle impostazioni dell'applicazione
script.log(script.getApplicationSettingsVariable("gitExecutablePath"));
1
2

Tieni presente che le impostazioni in realtà possono essere vuote, devi occupartene tu stesso. defaultValue viene utilizzato solo se l'impostazione non esiste affatto.

# Creazione di una directory della cache

È possibile memorizzare nella cache i file nella posizione cache predefinita del sistema.

# Chiamata al metodo e parametri

/**
 * Restituisce una directory cache per uno script
 *
 * @param {QString} subDir the subfolder to create and use
 * @return {QString} the cache dir path
 */
QString ScriptingService::cacheDir(const QString &subDir) const;
1
2
3
4
5
6
7

# Esempio

// crea la directory della cache per my-script-id
var cacheDirForScript = script.cacheDir("my-script-id");
1
2

# Cancellazione di una directory della cache

Puoi cancellare la directory della cache del tuo script passando il suo nome a clearCacheDir().

# Chiamata al metodo e parametri

/**
 * Cancella la directory della cache per uno script
 *
 * @param {QString} subDir the subfolder to clear
 * @return {bool} true on success
 */
bool ScriptingService::clearCacheDir(const QString &subDir) const;
1
2
3
4
5
6
7

# Esempio

// svuota la directory della cache di my-script-id
script.clearCacheDir("my-script-id");
1
2

# Leggere il percorso della directory del tuo script

Se è necessario ottenere il percorso della directory in cui è posizionato lo script, ad esempio per caricare altri file, è necessario registrare un file property string scriptDirPath;. Questa proprietà verrà impostata con il percorso della directory dello script.

# Esempio

import QtQml 2.0
import QOwnNotesTypes 1.0

Script {
    // the path to the script's directory will be set here
    property string scriptDirPath;

    function init() {
        script.log(scriptDirPath);
    }
}
1
2
3
4
5
6
7
8
9
10
11

# Conversione dei separatori di percorso in quelli nativi

# Chiamata al metodo e parametri

/**
* Restituisce il percorso con i separatori '/' convertiti in separatori che sono
* appropriato per il sistema operativo sottostante.
 *
 * On Windows, toNativeDirSeparators("c:/winnt/system32") returns
 * "c:\winnt\system32".
 *
 * @param path
 * @return
 */
QString ScriptingService::toNativeDirSeparators(QString path);
1
2
3
4
5
6
7
8
9
10
11

# Esempio

// tornerà "c:\winnt\system32" on Windows
script.log(script.toNativeDirSeparators("c:/winnt/system32"));
1
2

# Conversione dei separatori di percorso da quelli nativi

# Chiamata al metodo e parametri

/**
 * Restituisce il percorso usando '/' come separatore di file.
 * On Windows, for instance, fromNativeDirSeparators("c:\\winnt\\system32")
 * returns "c:/winnt/system32".
 *
 * @param path
 * @return
 */
QString ScriptingService::fromNativeDirSeparators(QString path);
1
2
3
4
5
6
7
8
9

# Esempio

// will return "c:/winnt/system32" on Windows
script.log(script.fromNativeDirSeparators("c:\\winnt\\system32"));
1
2

# Recupero del separatore di directory nativo

# Chiamata al metodo e parametri

/**
 * Restituisce il separatore di directory nativo "/" o "\" su Windows
 *
 * @return
 */
QString ScriptingService::dirSeparator();
1
2
3
4
5
6

# Esempio

// tornerà "\" on Windows
script.log(script.dirSeparator());
1
2

# Ottenere un elenco dei percorsi di tutte le note selezionate

# Chiamata al metodo e parametri

/**
 * Restituisce un elenco dei percorsi di tutte le note selezionate
 *
 * @return {QStringList} list of selected note paths
 */
QStringList ScriptingService::selectedNotesPaths();
1
2
3
4
5
6

# Esempio

// restituisce un elenco dei percorsi di tutte le note selezionate
script.log(script.selectedNotesPaths());
1
2

You may want to take a look at the example external-note-diff.qml (opens new window).

# Ottenere un elenco degli ID di tutte le note selezionate

# Chiamata al metodo e parametri

/**
 * Restituisce un elenco degli ID di tutte le note selezionate
 *
 * @return {QList<int>} list of selected note ids
 */
QList<int> ScriptingService::selectedNotesIds();
1
2
3
4
5
6

# Esempio

// restituisce un elenco degli ID di tutte le note selezionate
script.log(script.selectedNotesIds());
1
2

You may want to take a look at the example export-notes-as-one-html.qml (opens new window).

# Attivazione di un'azione di menu

# Chiamata al metodo e parametri

/**
 * Attiva un'azione di menu
 *
 * @param objectName {QString} object name of the action to trigger
 * @param checked {QString} only trigger the action if checked-state is
 *                          different than this parameter (optional, can be 0 or 1)
 */
void ScriptingService::triggerMenuAction(QString objectName, QString checked);
1
2
3
4
5
6
7
8

# Esempio

// attiva la modalità di sola lettura
script.triggerMenuAction("actionAllow_note_editing");

// disabilitare la modalità di sola lettura
script.triggerMenuAction("actionAllow_note_editing", 1);
1
2
3
4
5

You may want to take a look at the example disable-readonly-mode.qml (opens new window).

TIP

You can get the object names of the menu action from mainwindow.ui (opens new window). Basta cercare il titolo del menu in inglese. Nota che questi testi possono cambiare nel tempo.

# Apertura di una finestra di dialogo di input con una casella di selezione

# Chiamata al metodo e parametri

/**
 * Apre una finestra di dialogo di immissione con una casella di selezione
 *
 * @param title {QString} title of the dialog
 * @param label {QString} label text of the dialog
 * @param items {QStringList} list of items to select
 * @param current {int} index of the item that should be selected (default: 0)
 * @param editable {bool} if true the text in the dialog can be edited (default: false)
 * @return {QString} text of the selected item
 */
QString ScriptingService::inputDialogGetItem(
        const QString &title, const QString &label, const QStringList &items,
        int current, bool editable);
1
2
3
4
5
6
7
8
9
10
11
12
13

# Esempio

var result = script.inputDialogGetItem(
    "combo box", "Please select an item", ["Item 1", "Item 2", "Item 3"]);
script.log(result);
1
2
3

You may want to take a look at the example input-dialogs.qml (opens new window).

# Apertura di una finestra di dialogo di input con una riga di modifica

# Chiamata al metodo e parametri

/**
 * Apre una finestra di dialogo di immissione con una modifica della riga
 *
 * @param title {QString} title of the dialog
 * @param label {QString} label text of the dialog
 * @param text {QString} text in the dialog (optional)
 * @return
 */
QString ScriptingService::inputDialogGetText(
        const QString &title, const QString &label, const QString &text);
1
2
3
4
5
6
7
8
9
10

# Esempio

var result = script.inputDialogGetText(
    "line edit", "Please enter a name", "current text");
script.log(result);
1
2
3

# Verificare se esiste un file

# Chiamata al metodo e parametri

/**
 * Controlla se esiste un file
 * @param filePath
 * @return
 */
bool ScriptingService::fileExists(QString &filePath);
1
2
3
4
5
6

# Esempio

var result = script.fileExists(filePath);
script.log(result);
1
2

# Leggere il testo da un file

# Chiamata al metodo e parametri

/**
 * Leggi il testo da un file
 *
 * @param filePath {QString} path of the file to load
 * @param codec {QString} file encoding (default: UTF-8)
 * @return the file data or null if the file does not exist
 */
QString ScriptingService::readFromFile(const QString &filePath, const QString &codec)
1
2
3
4
5
6
7
8

# Esempio

if(script.fileExists(filePath)){
    var data = script.readFromFile(filePath);
    script.log(data);
}
1
2
3
4

# Scrittura di testo in un file

# Chiamata al metodo e parametri

/**
 * Scrive un testo in un file
 *
 * @param filePath {QString}
 * @param data {QString}
 * @param createParentDirs {bool} optional (default: false)
 * @return
 */
bool ScriptingService::writeToFile(const QString &filePath, const QString &data, bool createParentDirs);
1
2
3
4
5
6
7
8
9

# Esempio

var result = script.writeToFile(filePath, html);
script.log(result);
1
2

You may want to take a look at the example export-notes-as-one-html.qml (opens new window).

# Lavorare con websocket

Puoi controllare in remoto QOwnNotes utilizzando WebSocketServer.

Please take a look at the example websocket-server.qml (opens new window). Puoi testare il server socket collegandoti ad esso su Websocket test (opens new window).

Puoi anche ascoltare i socket con WebSocket. Please take look at the example websocket-client.qml (opens new window).

Tieni presente che per utilizzarla è necessario che sia installata la libreria QML websocket di Qt. Ad esempio in Ubuntu Linux puoi installare qml-module-qtwebsockets.

# Aggiunta di una regola di evidenziazione per l'editor

Puoi inserire direttamente le regole di evidenziazione nell'editor definendo espressioni regolari e assegnandole a uno stato di evidenziazione.

# Chiamata al metodo e parametri

/**
 * Aggiunge una regola di evidenziazione all'evidenziatore della sintassi dell'editor
 *
 * @param pattern {QString} the regular expression pattern to highlight
 * @param shouldContain {QString} a string that must be contained in the highlighted text for the pattern to be parsed
 * @param state {int} the state of the syntax highlighter to use
 * @param capturingGroup {int} the capturing group for the pattern to use for highlighting (default: 0)
 * @param maskedGroup {int} the capturing group for the pattern to use for masking (default: 0)
 */
void ScriptingService::addHighlightingRule(const QString &pattern,
                                           const QString &shouldContain,
                                           int state,
                                           int capturingGroup,
                                           int maskedGroup);
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# Highlighting states

Nome Nr.
NoState -1
Collegamento 0
Immagine 3
CodeBlock 4
CodeBlockComment 5
Corsivo 7
Grassetto 8
Liste 9
Comment 11
H1 12
H2 13
H3 14
H4 15
H5 16
H6 17
BlockQuote 18
HorizontalRuler 21
Tabella 22
InlineCodeBlock 23
MaskedSyntax 24
CurrentLineBackgroundColor 25
BrokenLink 26
FrontmatterBlock 27
TrailingSpace 28
CheckBoxUnChecked 29
CheckBoxChecked 30
StUnderline 31

# Esempio

// Evidenzia una riga di testo come "BLOCCO: del testo" come citazione in blocco (stato 18)
script.addHighlightingRule("^BLOCK: (.+)", "BLOCK:", 18);

// Mask out (state 24) all characters after 32 characters in a line
// capturingGroup 1 means the expression from the first bracketed part of the pattern will be highlighted
// maskedGroup -1 means that no masking should be done
script.addHighlightingRule("^.{32}(.+)", "", 24, 1, -1);
1
2
3
4
5
6
7

You can also take a look at the examples in highlighting.qml (opens new window).