SFWidgets.Menu service

The Menu service can be used to create and remove menus from the menubar of a LibreOfficeDev document window. Each menu entry can be associated with a script or with a UNO command. This service provides the following capabilities:

note

Menus created with this service are available only for a specified document window. They are not saved into the document or as application settings. Closing and opening the document will restore the default menubar settings.


warning

When OLE objects such as Math formulas or Calc charts are edited from within a document, LibreOfficeDev reconfigures the menubar according to the object. When this happens, the menus created with the Menu service are removed and are not be restored after editing the OLE object.


Invocazione del servizio

Prima di usare il servizio Menu è necessario caricare o importare le librerie ScriptForge:

note

• Basic macros require to load ScriptForge library using the following statement:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Python scripts require an import from scriptforge module:
from scriptforge import CreateScriptService


In Basic

The Menu service is instantiated by calling the CreateMenu method from the Document service. The code snippet below creates a menu named My Menu in the current document window with two entries Item A and Item B.


    Sub CreateMenu()
        GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
        Dim oDoc as Object, oMenu as Object
        Set oDoc = CreateScriptService("Document")
        Set oMenu = oDoc.CreateMenu("My Menu")
        With oMenu
            .AddItem("Item A", Command := "About")
            .AddItem("Item B", Script := "vnd.sun.star.script:Standard.Module1.ItemB_Listener?language=Basic&location=application")
            .Dispose()
        End With
    End Sub
  
note

After creating the menu, it is recommended to call the Dispose method to free the resources used by the Menu service instance.


In the example above, Item A is associated with the UNO command .uno:About whereas Item B is associated with the script ItemB_Listener defined in Module1 of the Standard library of the My Macros container.

The following example defines ItemB_Listener that will be called when Item B is clicked. This listener simply splits the argument string passed to the Sub and shows them in a message box.


    Sub ItemB_Listener(args As String)
        ' Process the argument string passed to the listener
        Dim sArgs as Object
        sArgs = Split(args, ",")
        MsgBox "Menu name: "   & sArgs(0) & Chr(13) & _
               "Menu item: "   & sArgs(1) & Chr(13) & _
               "Item ID: "     & sArgs(2) & Chr(13) & _
               "Item status: " & sArgs(3)
    End Sub
  

As shown in the example above, menu entries associated with a script receive a comma-separated string argument with the following values:

In Python

Gli esempi qui sopra possono essere scritti in Python come segue:


    from scriptforge import CreateScriptService
    
    def create_menu(args=None):
        oDoc = CreateScriptService("Document")
        oMenu = oDoc.CreateMenu("My Menu")
        oMenu.AddItem("Item A", command="About")
        oMenu.AddItem("Item B", script="vnd.sun.star.script:my_macros.py$item_b_listener?language=Python&location=user")
        oMenu.Dispose()
  

    def item_b_listener(args):
        bas = CreateScriptService("Basic")
        s_args = args.split(",")
        msg = f"Menu name: {s_args[0]}\n"
        msg += f"Menu item: {s_args[1]}\n"
        msg += f"Item ID: {s_args[2]}\n"
        msg += f"Item status: {s_args[3]}"
        bas.MsgBox(msg)
  

Proprietà

Nome

Sola lettura

Tipo

Descrizione

ShortcutCharacter

No

String

Carattere usato per definire la chiave di accesso alla voce del menu. Il carattere predefinito è "~".

SubmenuCharacter

No

String

Carattere o stringa che definisce in quale modo le voci del menu sono nidificate. Il carattere predefinito è ">".


Menu e sottomenu

Per creare un menu con dei sottomenu, usate il carattere definito nella proprietà SubmenuCharacter per creare la voce di menu che definisce dove saranno posizionati. Per esempio, prendete in considerazione la seguente gerarchia di menu/sottomenu.


    ' Item A
    ' Item B > Item B.1
    '          Item B.2
    ' ------ (line separator)
    ' Item C > Item C.1 > Item C.1.1
    '                     Item C.1.2
    ' Item C > Item C.2 > Item C.2.1
    '                     Item C.2.2
    '                     ------ (line separator)
    '                     Item C.2.3
    '                     Item C.2.4
  

Il codice sottostante usa il carattere predefinito ">" per i sottomenu in modo da creare la gerarchia menu/sottomenu definita in precedenza:


    oMenu.AddItem("Item A")
    oMenu.AddItem("Item B>Item B.1")
    oMenu.AddItem("Item B>Item B.2")
    oMenu.AddItem("---")
    oMenu.AddItem("Item C>Item C.1>Item C.1.1")
    oMenu.AddItem("Item C>Item C.1>Item C.1.2")
    oMenu.AddItem("Item C>Item C.2>Item C.2.1")
    oMenu.AddItem("Item C>Item C.2>Item C.2.2")
    oMenu.AddItem("Item C>Item C.2>---")
    oMenu.AddItem("Item C>Item C.2>Item C.2.3")
    oMenu.AddItem("Item C>Item C.2>Item C.2.4")
  
note

La stringa "---" è usata per definire delle linee di separazione nei menu o nei sottomenu.


Uso di icone

Le voci del menu possono avere delle icone, che sono specificate come argomenti dei metodi AddCheckBox, AddItem e AddRadioButton.

Tutte le icone disponibili in LibreOfficeDev possono essere usate specificando il loro percorso relativo alla cartella nella quale i file con le icone sono memorizzati all'interno della cartella d'installazione. Le icone si trovano nella seguente cartella:

INSTALLDIR/share/config

tip

Usate la proprietà InstallFolder del servizio FileSystem per determinare dove LibreOfficeDev è installato nel vostro sistema.


Questa cartella contiene una serie di file compressi (ZIP) che contengono i file con le immagini di ogni tema di icone. Le immagini all'interno dei file ZIP sono organizzate in cartelle. Per usare un'icona, specificate il suo file con il percorso della sua posizione all'interno del file ZIP.

L'esempio sottostante usa l'icona "sc_newdoc.svg" che si trova all'interno della cartella "cmd". Il carattere della barra inversa "/" è usato come separatore del percorso indipendentemente dal sistema operativo.

In Basic

      myMenu.AddItem("Item A", Icon := "cmd/sc_newdoc.svg")
    
In Python

      myMenu.AddItem("Item A", icon="cmd/sc_newdoc.svg")
    
note

Tutti i temi di icone hanno la stessa struttura interna. L'icona effettivamente visualizzata dipende dal tema di icone correntemente in uso.


Metodi

Elenco dei metodi del servizio Menu

AddCheckBox

AddItem

AddRadioButton


AddCheckBox

Inserisce una casella di controllo nel menu. Restituisce un valore intero che identifica l'elemento inserito.

Sintassi:

svc.AddCheckBox(menuitem: str, opt name: str, opt status: bool, opt icon: str, opt tooltip: str, opt command: str, opt script: str): int

Parametri:

menuitem: definisce il testo da visualizzare nel menu. Questo argomento definisce anche la gerarchia della voce all'interno del menu attraverso l'uso del carattere che indica i sottomenu.

name: valore in formato stringa utilizzata per identificare l'elemento del menu. Per impostazione predefinita, viene usato l'ultimo componente nella gerarchia del menu.

status: definisce se la voce è selezionata al momento della creazione del menu (Predefinito = False).

icon: percorso e nome dell'icona da visualizzare senza il separatore di percorso iniziale. L'icona effettivamente visualizzata dipende dal tema di icone in uso.

tooltip: testo da visualizzare come suggerimento.

command: The name of a UNO command without the .uno: prefix. If the command name does not exist, nothing happens.

script: The URI for a Basic or Python script that will be executed when the item is clicked.

note

The arguments command and script are mutually exclusive, hence only one of them can be set for each menu item.


tip

Read Scripting Framework URI Specification to learn more about the URI syntax used in the script argument.


Esempio:

In Basic

      ' Menu entry associated with the .uno:Paste command
      oMenu.AddCheckBox("Item A", Status := True, ToolTip := "Paste values", Command := "Paste")
      ' Runs the Basic script Standard.Module1.MyListener stored in the document
      oMenu.AddCheckBox("Item B", Status := False, Script := "vnd.sun.star.script:Standard.Module1.MyListener?language=Basic&location=document")
      ' Runs the Python script MyListener located in file myScripts.py in the user scripts folder
      oMenu.AddCheckBox("Item C", Status := True, Script := "vnd.sun.star.script:myScripts.py$MyListener?language=Python&location=user")
    
In Python

      oMenu.AddCheckBox("Item A", status=True, tooltip="Paste values", command="Paste")
      oMenu.AddCheckBox("Item B", status=False, script="vnd.sun.star.script:Standard.Module1.MyListener?language=Basic&location=document")
      oMenu.AddCheckBox("Item C", Status=True, Script="vnd.sun.star.script:myScripts.py$MyListener?language=Python&location=user")
    

AddItem

Inserisce una voce di didascalia nel menu. Restituisce un valore intero che identifica l'elemento inserito.

Sintassi:

svc.AddItem(menuitem: str, opt name: str, opt icon: str, opt tooltip: str, opt command: str, opt script: str): int

Parametri:

menuitem: definisce il testo da visualizzare nel menu. Questo argomento definisce anche la gerarchia della voce all'interno del menu attraverso l'uso del carattere che indica i sottomenu.

name: valore in formato stringa da restituire quando la voce riceve un clic. Per impostazione predefinita, viene usato l'ultimo componente nella gerarchia del menu.

icon: percorso e nome dell'icona da visualizzare senza il separatore di percorso iniziale. L'icona effettivamente visualizzata dipende dal tema di icone in uso.

tooltip: testo da visualizzare come suggerimento.

command: The name of a UNO command without the .uno: prefix. If the command name does not exist, nothing happens.

script: The URI for a Basic or Python script that will be executed when the item is clicked.

note

The arguments command and script are mutually exclusive, hence only one of them can be set for each menu item.


tip

Read Scripting Framework URI Specification to learn more about the URI syntax used in the script argument.


Esempio:

In Basic

      oMenu.AddItem("Voce A", Tooltip := "Messaggio descrittivo")
    
In Python

      oMenu.AddItem("Voce A", tooltip = "Messaggio descrittivo")
    

AddRadioButton

Inserisce una voce con pulsante di scelta nel menu. Restituisce un valore intero che identifica la voce inserita.

Sintassi:

svc.AddRadioButton(menuitem: str, opt name: str, opt status: str, opt icon: str, opt tooltip: str, opt command: str, opt script: str): int

Parametri:

menuitem: definisce il testo da visualizzare nel menu. Questo argomento definisce anche la gerarchia della voce all'interno del menu attraverso l'uso del carattere che indica i sottomenu.

name: valore in formato stringa da restituire quando la voce riceve un clic. Per impostazione predefinita, viene usato l'ultimo componente nella gerarchia del menu.

status: specifica se la voce è selezionata al momento della creazione del menu (Predefinito = False).

icon: percorso e nome dell'icona da visualizzare senza il separatore di percorso iniziale. L'icona effettivamente visualizzata dipende dal tema di icone in uso.

tooltip: testo da visualizzare come suggerimento.

command: The name of a UNO command without the .uno: prefix. If the command name does not exist, nothing happens.

script: The URI for a Basic or Python script that will be executed when the item is clicked.

note

The arguments command and script are mutually exclusive, hence only one of them can be set for each menu item.


tip

Read Scripting Framework URI Specification to learn more about the URI syntax used in the script argument.


Esempio:

In Basic

      oMenu.AddRadioButton("Item A", Name := "A", Status := True)
    
In Python

      oMenu.AddRadioButton("Item A", name="A", status=True)
    
warning

Tutte le routine e gli identificatori Basic di ScriptForge che iniziano con un carattere di sottolineatura "_" sono riservati per uso interno. Non è previsto il loro utilizzo nelle macro in Basic o negli script in Python.