Contenido

# Servicio SFWidgets.PopupMenu

The PopupMenu service can be used to create popup menus that can be associated with events or executed by scripts. This service provides the following capabilities:

- Creation of popup menus with custom entries, checkboxes and radio buttons.

- Decoration of menu items with icons and tooltips.

## Invocación del servicio

Antes de utilizar el servicio PopupMenu, es necesario cargar o importar la biblioteca ScriptForge:

• Para cargar la biblioteca ScriptForge que necesitan las macros de Basic se debe usar la siguiente declaración:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
• Los scripts de Python necesitan importar el módulo scriptforge:
from scriptforge import CreateScriptService

##### En BASIC

The PopupMenu service can be instantiated in multiple ways. The example below creates a popup menu without associating it with a mouse or application event.

        Sub ShowPopup
            GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
            Dim myPopup As Object
            Set myPopup = CreateScriptService("SFWidgets.PopupMenu", , 300, 300)
            myPopup.AddItem("Item ~A")
            myPopup.AddItem("Item ~B")
            vResponse = myPopup.Execute()
            MsgBox("Selected item ID: " & vResponse)
            myPopup.Dispose()
        End Sub

Running the Sub defined above will create a popup menu with two entries in the position X=300 and Y=300 on the screen.

The prefix SFWidgets can be suppressed while invoking the PopupMenu service.

The following example defines a Sub that can be associated with a mouse event:

        Sub MyPopupClick(Optional poMouseEvent as Object)
            Dim myPopup As Object
            Set myPopup = CreateScriptService("PopupMenu", poMouseEvent)
            ' Populate popupmenu with items
            Dim vResponse As Variant
            vResponse = myPopup.Execute(False)
            ' Do something based on vResponse
            ' ...
            myPopup.Dispose()
        End Sub

Use the Dispose method to free resources after executing the popup menu.

It is also possible to associate a popup menu with events triggered by LibreOffice applications, form and dialog controls. Events such as "Mouse button pressed" and "Mouse button released" are commonly associated with popup menus.

        Sub MyPopupClick(Optional poEvent as Object)
            Dim myPopup As Object
            Set myPopup = CreateScriptService("PopupMenu", poEvent)
            ' ...
        End Sub

##### En Python

Los ejemplos anteriores pueden escribirse en Python de esta manera:

        from scriptforge import CreateScriptService

        def show_popup(args=None):
            my_popup = CreateScriptService("SFWidgets.PopupMenu", None, 300, 300)
            bas = CreateScriptService("Basic")
            my_popup.AddItem("Item ~A")
            my_popup.AddItem("Item ~B")
            response = my_popup.Execute()
            bas.MsgBox(f"Selected item ID: {response}")
            my_popup.Dispose()

        def my_popup_click(poEvent=None):
            my_popup = CreateScriptService("SFWidgets.PopupMenu", poEvent)
            # Populate popupmenu with items
            response = my_popup.Execute()
            # Hacer algo en función de una respuesta
            my_popup.Dispose()

## Propiedades

Nombre | De solo lectura | Tipo | Descripción
--- | --- | --- | ---
ShortcutCharacter | No | String | Character used to define the access key of a menu item. The default character is ~.
SubmenuCharacter | No | String | Character or string that defines how menu items are nested. The default character is >.

## Menús y submenús

To create a popup 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

El código siguiente utiliza el carácter predeterminado para submenús > para crear la jerarquía de menús y submenús definida anteriormente:

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

La cadena --- se utiliza para definir líneas separadoras en los menús y submenús.

## Utilizar iconos

Items in the menu can have icons, which are specified as arguments in the AddCheckBox, AddItem and AddRadioButton methods.

Todos los iconos disponibles en LibreOffice pueden utilizarse especificando su ruta relativa a la carpeta donde se encuentran los archivos de iconos en la carpeta de instalación. Los iconos se encuentran en la siguiente carpeta:

INSTALLDIR/share/config

Utilice la propiedad InstallFolder del servicio FileSystem para determinar dónde está instalado LibreOffice en su sistema.

This folder contains a series of ZIP files containing the image files of each available icon set. The images inside these ZIP files are organized into folders. To use an icon, specify the icon file with the path to its location inside the ZIP file.

The example below uses the icon "sc_newdoc.svg" that is located inside the "cmd" folder. The forward slash "/" character is used as the path separator regardless of the operating system.

##### En BASIC

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

##### En Python

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

Todos los conjuntos de iconos tienen la misma estructura interna. El icono mostrado depende del conjunto de iconos en uso actualmente.

## Métodos

Lista de métodos en el servicio PopupMenu
AddCheckBox AddItem | AddRadioButton | Execute

## AddCheckBox

Inserta una casilla en el menú emergente. Devuelve un valor entero que identifica el elemento insertado.

### Sintaxis:

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

### 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.

name: String value to be returned when the item is clicked. By default, the last component of the menu hierarchy is used.

status: Defines whether the item is selected when the menu is created (Default = False).

icon: Path and name of the icon to be displayed without the leading path separator. The actual icon shown depends on the icon set being used.

tooltip: Text to be displayed as tooltip.

### Ejemplo:

##### En BASIC

          myPopup.AddCheckBox("Option A", Status := True)

##### En Python

          my_popup.AddCheckBox("Option A", status=True)

## AddItem

Inserts a menu entry in the popup menu. Returns an integer value that identifies the inserted item.

### Sintaxis:

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

### 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.

name: String value to be returned when the item is clicked. By default, the last component of the menu hierarchy is used.

icon: Path and name of the icon to be displayed without the leading path separator. The actual icon shown depends on the icon set being used.

tooltip: Text to be displayed as tooltip.

### Ejemplo:

##### En BASIC

          myPopup.AddItem("Item A", Tooltip := "Un mensaje descriptivo")

##### En Python

          my_popup.AddItem("Item A", tooltip = "A descriptive message")

## AddRadioButton

Inserta una entrada de botón de opción en el menú emergente. Devuelve un valor entero que identifica el elemento insertado.

### Sintaxis:

svc.AddRadioButton(menuitem: str, opt name: str, opt status: bool = False, opt icon: str, opt tooltip: str): int

### 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.

name: String value to be returned when the item is clicked. By default, the last component of the menu hierarchy is used.

status: Defines whether the item is selected when the menu is created (Default = False).

icon: Path and name of the icon to be displayed without the leading path separator. The actual icon shown depends on the icon set being used.

tooltip: Text to be displayed as tooltip.

### Ejemplo:

##### En BASIC

          myPopup.AddRadioButton("Option A", Name := "A", Status := True)

##### En Python

          my_popup.AddRadioButton("Option A", name="A", status=True)

## Execute

Muestra el menú emergente y espera alguna acción por parte del usuario. Devuelve el elemento en que se ha pulsado.

If the user clicks outside the popup menu or presses the Esc key, then no item is selected. In such cases, the returned value depends on the returnid parameter. If returnid = True and no item is selected, then the value 0 (zero) is returned. Otherwise an empty string "" is returned.

### Sintaxis:

svc.Execute(opt returnid: bool = True): any

### Parámetros:

returnid: If True the selected item ID is returned. If False the method returns the item's name (Default = True).

### Ejemplo:

In the examples below, a popup menu is created and the item's name is returned because the returnid argument is set to False.

##### En BASIC

          myPopup.AddItem("Item A", Name := "A")
          myPopup.AddItem("Item B", Name := "B")
          Dim vResponse as Variant
          vResponse = myPopup.Execute(False)

##### En Python

          my_popup.AddItem("Item A", name="A")
          my_popup.AddItem("Item B", name="B")
          response = my_popup.Execute(False)

Todas las rutinas o identificadores BASIC de ScriptForge precedidas por guion bajo «_» están reservadas para uso interno. No deben utilizarse en macros BASIC o secuencias Python.

Temas relacionados

Servicio SFDialogs.Dialog

Servicio SFDialogs.DialogControl

Servicio SFWidgets.Menu

¡Necesitamos su ayuda!