WdyKT‖SFWidgets.ContextMenu service

MJaiF‖Context menus are predefined at LibreOfficeDev installation. They can be customized in the Tools + Customize dialog.

P8AG5‖The ContextMenu service provides the following capabilities:

SCBB3‖The new menu settings are not saved anywhere. Neither in the document nor in the LibreOfficeDev settings.

4KFw4‖A context menu is usually triggered by a right-click on a specific area of a document. Consider clicking in a cell or on a sheet tab in a Calc document.

De8Ad‖Service invocation

VjxCN‖Before using the ContextMenu service the ScriptForge library needs to be loaded or imported:

Note Icon

gF8D8‖• 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


3aa4B‖In Basic

rGXGT‖The ContextMenu service is instantiated from the SF_Document.ContextMenus() and SF_Datasheet.ContextMenus() methods only.


    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
  

REfNp‖Running the Sub defined above redefines the context menu related to a specific area in the document, here a cell belonging to a Calc document.

5x7PF‖The new definition will remain active until the document is closed or until the context menu is redefined again.

Tip Icon

cdXEQ‖Use the Dispose method to free resources after executing the context menu.


BenDd‖In Python

EEyb7‖The example above can be written in Python as follows:


    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()
  

XFprc‖Properties

roesJ‖Name

Zu9RF‖Readonly

vWRqB‖Type

dAXkA‖Description

ParentDocument

dZUPG‖Yes

Object

cRtgX‖The parent document class (or one of its subclasses) instance.

ShortcutCharacter

XEKy4‖Yes

String

M9FSD‖Character used to define the access key of a menu item. The default character is ~.

SubmenuCharacter

RfvMe‖Yes

String

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


x4HBM‖Menu and Submenus

8TjxT‖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
  

KnTJY‖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")
  
Note Icon

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


SA2cX‖Using icons

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

nr4Dw‖Methods

tDvjd‖List of Methods in the ContextMenu Service

Activate

AddItem

RemoveAllItems


Activate

JhCRr‖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.

FVEx2‖Syntax:

svc.Activate(opt enable: bool = True)

WADQ4‖Parameters:

Didmr‖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 LibreOfficeDev level takes the precedence.

AddItem

Ek9UR‖Inserts a menu entry in the context menu.

FVEx2‖Syntax:

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

WADQ4‖Parameters:

8RExm‖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.

LKYs2‖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.

Q5w45‖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.

EFSA4‖Example:

3aa4B‖In Basic

      rto8C‖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")
    
BenDd‖In Python

      AF6DS‖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

pM7aY‖Remove all items, both

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

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

FVEx2‖Syntax:

svc.RemoveAllItems()

EFSA4‖Example:

T9Cvr‖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.

3aa4B‖In 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
    
BenDd‖In 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)
    
Warning Icon

uzETY‖All ScriptForge Basic routines or identifiers that are prefixed with an underscore character "_" are reserved for internal use. They are not meant be used in Basic macros or Python scripts.


Please support us!

Please support us!