SFWidgets.ContextMenu serviço

Os menus de contexto são predefinidos durante a instalação do LibreOffice. Eles podem ser personalizados na caixa de diálogo Ferramentas + Personalizar.

O serviço ContextMenu oferece os seguintes recursos:

As novas configurações do menu não são salvas em lugar nenhum. Nem no documento, nem nas configurações do LibreOffice.

Um menu de contexto geralmente é ativado ao clicar com o botão direito do mouse em uma área específica de um documento. Experimente clicar em uma célula ou na aba de uma planilha em um documento do Calc.

Chamada de serviço

Antes de usar o serviço ContextMenu, é necessário carregar ou importar a biblioteca ScriptForge:

Ícone Nota

• Macros BASIC precisam carregar a biblioteca ScriptForge usando a seguinte instrução:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Scripts Python exigem uma importação do módulo scriptforge:
from scriptforge import CreateScriptService


Em Basic

O serviço ContextMenu é instanciado apenas a partir dos métodos SF_Document.ContextMenus() e SF_Datasheet. ContextMenus().


    Sub DefineContextMenu()
        GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
        Dim calc As Object, menu As Object
        Set calc = CreateScriptService("Document", ThisComponent)
        Set menu = calc.ContextMenus("cell")  ' Right-click on a cell
        '  ... Define the context menu ...
        menu.Dispose()
    End Sub
  

A execução do Sub definido acima redefine o menu de contexto relacionado a uma área específica do documento, neste caso, uma célula pertencente a um documento Calc.

A nova definição permanecerá ativa até que o documento seja fechado ou até que o menu de contexto seja redefinido novamente.

Ícone Dica

Use o método Dispose para liberar recursos após a execução do menu de contexto.


Em Python

O exemplo acima pode ser escrito em Python da seguinte forma:


    from scriptforge import CreateScriptService
    
    def DefineContextMenu(args=None):
        basic = CreateScriptService("Basic")
        calc = CreateScriptService("Document", basic.ThisComponent)
        menu = calc.ContextMenus("cell")  # Right-click on a cell
        #  ... Define the context menu ...
        menu.Dispose()
  

Propriedades

Nome

Apenas leitura

Tipo

Descrição

ParentDocument

Sim

Object

A instância da classe do documento pai (ou de uma de suas subclasses).

ShortcutCharacter

Sim

String

Caractere usado para definir a tecla de atalho de um item de menu. O caractere padrão é ~.

SubmenuCharacter

Sim

String

Character or string that defines how menu items are nested. The default character is >.


Menu and Submenus

To create a context menu with submenus, use the character defined in the SubmenuCharacter property while creating the menu entry to define where it will be placed. For instance, consider the following menu/submenu hierarchy.


    ' 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
  

The code below uses the default submenu character > to create the menu/submenu hierarchy defined above:


    menu.AddItem("Item A")
    menu.AddItem("Item B>Item B.1")
    menu.AddItem("Item B>Item B.2")
    menu.AddItem("---")
    menu.AddItem("Item C>Item C.1>Item C.1.1")
    menu.AddItem("Item C>Item C.1>Item C.1.2")
    menu.AddItem("Item C>Item C.2>Item C.2.1")
    menu.AddItem("Item C>Item C.2>Item C.2.2")
    menu.AddItem("Item C>Item C.2>---")
    menu.AddItem("Item C>Item C.2>Item C.2.3")
    menu.AddItem("Item C>Item C.2>Item C.2.4")
  
Ícone Nota

The string --- is used to define separator lines in menus or submenus.


Using icons

Unlike popup menus, context menu items must not contain any icons.

Métodos

List of Methods in the ContextMenu Service

Activate

AddItem

RemoveAllItems


Activate

Make the added items of the context menu stored in the document available for execution, or, at the opposite, disable them, depending on the argument.

Sintaxe:

svc.Activate(opt enable: bool = True)

Parâmetros:

enable: When True (default), the local menu stored in the document is made active. When False, the local menu is ignored and the global menu defined at LibreOffice level takes the precedence.

AddItem

Inserts a menu entry in the context menu.

Sintaxe:

svc.AddItem(menuitem: str, opt command: str, opt script: str)

Parâmetros:

menuitem: Defines the text to be displayed in the menu. This argument also defines the hierarchy of the item inside the menu by using the submenu character. Set the last component to "---" to define a line separator.

command: The name of the UNO command that will be run when the item is clicked, without the .uno: prefix. If the command name does not exist or is not applicable, nothing will happen.

script: The URI for a Basic or Python script that will be executed when the item is clicked. Note that the given script will not get any argument.

Exemplo:

Em Basic

      menu.AddItem("Menu top>Item 1", command := "About")
      menu.AddItem("Menu top>Item 2", script := "vnd.sun.star.script:myLib.Module1.ThisSub?language=Basic&location=document")
    
Em Python

      menu.AddItem('Menu top>Item 1', command = 'About')
      menu.AddItem('Menu top>Item 2', script = 'vnd.sun.star.script:Module1.py$thisdef?language=Python&location=document')
    

RemoveAllItems

Remove all items, both

This action cannot be reverted except by closing and reopening the document.

Afterwards, when relevant, use AddItem() to insert new menu items.

Sintaxe:

svc.RemoveAllItems()

Exemplo:

Associate next Sub/def with the on-right-click event of a sheet. The custom menu appears when right-clicking in column C of the Calc sheet, otherwise the normal behaviour is preserved.

Em Basic

      Sub OnRightClick1(Optional XRange)  '  Xrange is a com.sun.star.table.XCellRange object
      Dim calc As Object, menu As Object, in_column As Boolean
      Set calc = CreateScriptService("Calc", ThisComponent)
      Set menu = calc.ContextMenus("cell")
      menu.RemoveAllItems()
      in_column = ( Len(calc.Intersect("Sheet1.$C:$C", XRange.AbsoluteName)) > 0 )
      If in_column Then
          menu.AddItem("A", script := "vnd.sun.star.script:Standard.Module1.EnterA?language=Basic&location=document")
          ' ...
      End If
      menu.Activate(in_column)
      End Sub
    
Em Python

        def OnRightClick1(XRange = None)  #  Xrange is a com.sun.star.table.XCellRange object
            basic = CreateScriptService('basic')
            calc = CreateScriptService('Calc', basic.ThisComponent)
            menu = calc.ContextMenus('cell')
            menu.RemoveAllItems()
            in_column = ( len(calc.Intersect("Sheet1.$C:$C", XRange.AbsoluteName)) > 0 )
            if in_column:
                menu.AddItem('A', script = 'vnd.sun.star.script:Module1.py$EnterA?language=Python&location=document")
                # ...
            menu.Activate(in_column)
    
Ícone Aviso

Todas as rotinas ou identificadores do ScriptForge em Basic que possuem o caractere "_" como prefixo são reservados para uso interno. Elas não devem ser usadas em macros escritas em Basic ou em Python.


♥ Doe para nosso projeto! ♥

♥ Doe para nosso projeto! ♥