Usługa SFDialogs.DialogControl

Usługa DialogControl zarządza formantami należącymi do okna dialogowego zdefiniowanego za pomocą edytora okien dialogowych Basic. Każde wystąpienie bieżącej usługi reprezentuje pojedynczy formant w oknie dialogowym.

Usługa koncentruje się na pobieraniu i ustawianiu wartości wyświetlanych w formantach okna. Elementy można formatować za pomocą właściwości XControlModel i XControlView.

Należy pamiętać, że zawartość unikalnej właściwości DialogControl.Value różni się w zależności od typu formantu.

Szczególną uwagę zwrócono na formantu kontroli drzewa typów. Łatwo jest obsadzić drzewo, albo gałąź po gałęzi, albo zestawem gałęzi na raz. Wypełnianie formantu drzewa może odbywać się statycznie lub dynamicznie.

tip

Usługa SFDialogs.DialogControl jest ściśle powiązana z usługą SFDialogs.Dialog.


Wywoływanie usługi

Przed użyciem usługi DialogControl należy załadować lub zaimportować bibliotekę ScriptForge:

note

• Podstawowe makra wymagają załadowania biblioteki ScriptForge przy użyciu następującej instrukcji:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Skrypty Pythona wymagają importu z modułu scriptforge:
from scriptforge import CreateScriptService


Usługa DialogControl jest wywoływana z istniejącej instancji usługi Dialog poprzez jej metodę Controls(). Okno dialogowe musi zostać zainicjowane za pomocą usługi SFDialogs.Dialog.


      Dim myDialog As Object, myControl As Object
      Set myDialog = CreateScriptService("SFDialogs.Dialog", "GlobalScope", myLibrary, DialogName)
      Set myControl = myDialog.Controls("myTextBox")
      myControl.Value = "Okno dialogowe uruchomiono " & Now()
      myDialog.Execute()
      ' ... przetwarzanie wartości formantów
      myDialog.Terminate()
   

     from time import localtime, strftime
     dlg = CreateScriptService('SFDialogs.Dialog', 'GlobalScope', lib_name, dlg_name)
     text = dlg.Controls('myTextBox')
     text.Value = "Okno dialogowe uruchomiono " + strftime("%a, %d %b %Y %H:%M:%S", localtime())
     dlg.Execute()
     # ... przetwarzanie wartości formantów
     dlg.Terminate()
   

Pobieranie instancji DialogControl, która wyzwoliła zdarzenie formantu

Instancję usługi DialogControl można pobrać poprzez usługę SFDialogs.DialogEvent, pod warunkiem, że okno dialogowe zostało zainicjowane za pomocą usługi Dialog. W poniższym przykładzie oControl zawiera instancję DialogControl, która wyzwoliła zdarzenie formantu.


      Sub aControlEventHandler(ByRef poEvent As Object)
          Dim oControl As Object
          Set oControl = CreateScriptService("SFDialogs.DialogEvent", poEvent)
          ' ...
      End Sub
  

Lub używając Pythona:


     def control_event_handler(event: uno):
         oControl = CreateScriptService('SFDialogs.DialogEvent', event)
         # ...
  

Należy pamiętać, że w poprzednich przykładach przedrostek "SFDialogs." można pominąć, jeśli uzna się to za stosowne.

Obsługa wyjątków w procedurach obsługi zdarzeń

Podczas tworzenia procedury obsługi zdarzeń formantów dobrą praktyką jest obsługa błędów wewnątrz samego podprogramu. Załóżmy na przykład, że po kliknięciu przycisku wywoływana jest procedura obsługi zdarzeń poniżej.


    Sub OnButtonClicked(ByRef oEvent As Object)
    On Local Error GoTo Catch
        Dim oControl As Object
        oControl = CreateScriptService("DialogEvent", oEvent)
        ' Przetwarzanie zdarzeń
        Exit Sub
    Catch:
        MsgBox SF_Exception.Description
        SF_Exception.Clear
    End Sub
  
tip

Wywołaj SF_Exception.Clear, jeśli nie chcesz, aby błąd rozprzestrzeniał się po zakończeniu wykonywania okna dialogowego.


W Pythonie użyj natywnych bloków try/except do obsługi wyjątków, jak pokazano poniżej:


    def on_button_clicked(event=None):
        try:
            oControl = CreateScriptService("DialogEvent", event)
            # Przetwórz zdarzenie
        except Exception as e:
            # Obiekt "bas" poniżej jest instancją usługi Basic
            bas.MsgBox(str(e))
  

Typy formantów

Usługa DialogControl jest dostępna dla następujących typów formantów:

Właściwości

Nazwa

Tylko do odczytu

Typ

Stosuje się do

Opis

Cancel

Nie

Boolean

Button

Określa, czy przycisk polecenia ma działanie przycisku Anuluj.

Caption

Nie

String

Button, CheckBox, FixedLine, FixedText, GroupBox, RadioButton

Określa tekst skojarzony z formantem.

ControlType

Tak

String

Wszystko

Jeden z typów wymienionych powyżej.

CurrentNode

Nie

Obiekt
UNO

TreeControl

Aktualnie najwyższy węzeł wybrany w formancie drzewa. Szczegółowe informacje można znaleźć w dokumentacji interfejsu programowania aplikacji (API) XmutableTreeNode.

Default

Nie

Boolean

Button

Określa, czy przycisk polecenia jest przyciskiem domyślnym (OK).

Enabled

Nie

Boolean

Wszystko

Określa, czy formant jest dostępny za pomocą kursora.

Format

Nie

String

DateField, TimeField, FormattedField

(tylko do odczytu)

Określa format używany do wyświetlania dat i godzin. Musi to być jeden z tych ciągów:

W przypadku dat: "Standard (short)", "Standard (short YY)", "Standard (short YYYY)", "Standard (long)", "DD/MM/YY", "MM/DD/YY", "YY/MM/DD", "DD/MM/YYYY", "MM/DD/YYYY" , "YYYY/MM/DD", "YY-MM-DD", "YYYY-MM-DD".

W przypadku godzin: "24h short", "24h long", "12h short", "12h long".

ListCount

Tak

Long

ComboBox, ListBox, TableControl

Określa liczbę wierszy w ListBox, ComboBox lub TableControl.

ListIndex

Nie

Long

ComboBox, ListBox, TableControl

Określa, który element jest wybrany w ListBox, ComboBox lub TableControl.

Locked

Nie

Boolean

ComboBox, CurrencyField, DateField, FileControl, FormattedField, ListBox, NumericField, PatternField, TextField, TimeField

Określa, czy formant jest tylko do odczytu.

MultiSelect

Nie

Boolean

ListBox

Określa, czy użytkownik może dokonać wielu wyborów w polu listy.

Name

Tak

String

Wszystko

Nazwa formantu.

Page

Nie

Integer

Wszystko

Okno dialogowe może składać się z kilku stron, po których użytkownik może przechodzić krok po kroku. Właściwość Page obiektu Dialog określa, która strona okna dialogowego jest aktywna.

Właściwość Page formantu definiuje stronę okna dialogowego, na której formant jest widoczny.

Parent

Yes

Dialog
service

All

The parent SFDialogs.Dialog class object instance.

Picture

No

String

Button, ImageControl

Specifies the file name containing a bitmap or other type of graphic to be displayed on the specified control. The filename must comply with the FileNaming attribute of the ScriptForge.FileSystem service.

RootNode

Yes

UNO
object

TreeControl

An object representing the lowest root node (usually there is only one such root node). Refer to XmutableTreeNode in Application Programming Interface (API) documentation for detailed information.

RowSource

No

Array of strings

ComboBox, ListBox

Specifies the data contained in a combobox or a listbox.

Text

Yes

String

ComboBox, FileControl, FormattedField, PatternField, TextField

Gives access to the text being displayed by the control.

TipText

No

String

All

Specifies the text that appears as a tooltip when you hold the mouse pointer over the control.

TripleState

No

Boolean

CheckBox

Specifies if the checkbox control may appear dimmed (grayed) or not.

Value

No

Variant

Refer to Value property

Visible

No

Boolean

All

Specifies if the control is hidden or visible.

XControlModel

Yes

UNO
object

All

The UNO object representing the control model. Refer to XControlModel and UnoControlDialogModel in Application Programming Interface (API) documentation for detailed information.

XControlView

Yes

UNO
object

All

The UNO object representing the control view. Refer to XControl and UnoControlDialog in Application Programming Interface (API) documentation for detailed information.

XTreeDataModel

Yes

UNO
object

TreeControl

The UNO object representing the tree control data model. Refer to XMutableTreeDataModel in Application Programming Interface (API) documentation for detailed information.


The Value property

Control type

Type

Opis

Button

Boolean

For toggle buttons only

CheckBox

Boolean or Integer

0, False: not checked
1, True: checked
2: grayed, don't know

ComboBox

String

The selected value. The ListIndex property is an alternate option.

CurrencyField

Numeric

DateField

Date

FileControl

String

A file name formatted in accordance with the FileNaming property of the ScriptForge.FileSystem service

FormattedField

String or Numeric

ListBox

String or array of strings

The selected row(s) as a scalar or as an array depending on the MultiSelect attribute

NumericField

Numeric

PatternField

String

ProgressBar

Numeric

Must be within the predefined bounds

RadioButton

Boolean

Each button has its own name. They are linked together if their TAB positions are contiguous. If a radiobutton is set to True, the other related buttons are automatically set to False

ScrollBar

Numeric

Must be within the predefined bounds

TableControl

Array

One-dimensional array with the data of the currently selected row.

TextField

String

The text appearing in the field

TimeField

Date


Event properties

Returns a URI string with the reference to the script triggered by the event. Read its specification in the scripting framework URI specification.

Nazwa

ReadOnly

Description as labeled in the Basic IDE

OnActionPerformed

Yes

Execute action

OnAdjustmentValueChanged

Yes

While adjusting

OnFocusGained

Yes

When receiving focus

OnFocusLost

Yes

When losing focus

OnItemStateChanged

Yes

Item status changed

OnKeyPressed

Yes

Key pressed

OnKeyReleased

Yes

Key released

OnMouseDragged

Yes

Mouse moved while key presses

OnMouseEntered

Yes

Mouse inside

OnMouseExited

Yes

Mouse outside

OnMouseMoved

Yes

Mouse moved

OnMousePressed

Yes

Mouse button pressed

OnMouseReleased

Yes

Mouse button released

OnNodeExpanded

No

(Not in Basic IDE) when the expansion button is pressed on a node in a tree control

OnNodeSelected

No

(Not in Basic IDE) when a node in a tree control is selected

OnTextChanged

Yes

Text modified


Metody

List of Methods in the DialogControl Service

AddSubNode
AddSubTree
CreateRoot

FindNode
SetFocus

SetTableData
WriteLine


AddSubNode

Create and return a new node of the tree control as a UNO object subordinate to a parent node. Refer to XMutableTreeNode in Application Programming Interface (API) documentation for detailed information.

This method may be called before displaying the dialog box to build the initial tree. It may also be called from a dialog or control event - using the OnNodeExpanded event - to complete the tree dynamically.

Składnia:

svc.AddSubNode(parentnode: uno, displayvalue: str, opt datavalue: any): uno

Parametry:

parentnode: A node UNO object, of type com.sun.star.awt.tree.XMutableTreeNode.

displayvalue: The text appearing in the tree control box.

datavalue: Any value associated with the new node. datavalue may be a string, a number or a date. Omit the argument when not applicable.

Przykład:

LibreOffice Basic and Python examples pick up current document's myDialog dialog from Standard library.

W języku Basic

      Dim oDlg As Object, myTree As Object, myNode As Object, theRoot As Object
      Set oDlg = CreateScriptService("Dialog",,, "myDialog")
      Set myTree = oDlg.Controls("myTreeControl")
      Set theRoot = myTree.CreateRoot("Tree top")
      Set myNode = myTree.AddSubNode(theRoot, "A branch ...")
   
W języku Python

     dlg = CreateScriptService('SFDialogs.Dialog', None, None, 'myDialog')
     tree = dlg.Controls('myTreeControl')
     root = tree.CreateRoot('Tree top')
     node = tree.AddSubNode(root, 'A branch ...')
   

AddSubTree

Return True when a subtree, subordinate to a parent node, could be inserted successfully in a tree control. If the parent node had already child nodes before calling this method, the child nodes are erased.

This method may be called before displaying the dialog box to build the initial tree. It may also be called from a dialog or control event - using the OnNodeExpanded event - to complete the tree dynamically.

Składnia:

svc.AddSubTree(parentnode: uno, flattree: any, opt withdatavalue: bool): bool

Parametry:

parentnode: A node UNO object, of type com.sun.star.awt.tree.XMutableTreeNode.

flattree: a two dimension array sorted on the columns containing the display values. Such an array can be issued by the GetRows method applied on the SFDatabases.Database service. When an array item containing the text to be displayed is Empty or Null, no new subnode is created and the remainder of the row is skipped.


      Flat tree    >>>>    Resulting subtree
      A1	B1	C1             |__   A1	
      A1	B1	C2                   |__   B1
      A1	B2	C3                         |__  C1
      A2	B3	C4                         |__  C2
      A2	B3	C5                   |__   B2
      A3	B4	C6                         |__  C3
                             |__   A2
                                   |__   B3
                                         |__  C4
                                         |__  C5
                             |__   A3
                                   |__   B4
                                         |__  C6
   

withdatavalue: When False default value is used, every column of flattree contains the text to be displayed in the tree control. When True, the texts to be displayed (displayvalue) are in columns 0, 2, 4, ... while the data values (datavalue) are in columns 1, 3, 5, ...

Przykład:

W języku Basic

      Dim myTree As Object, theRoot As Object, oDb As Object, vData As Variant
      Set myTree = myDialog.Controls("myTreeControl")
      Set theRoot = myTree.CreateRoot("By product category")
      Set oDb = CreateScriptService("SFDatabases.Database", "/home/.../mydatabase.odb")
      vData = oDb.GetRows("SELECT [Category].[Name], [Category].[ID], [Product].[Name], [Product].[ID] " _
          & "FROM [Category], [Product] WHERE [Product].[CategoryID] = [Category].[ID] " _
          & "ORDER BY [Category].[Name], [Product].[Name]")
      myTree.AddSubTree(theRoot, vData, WithDataValue := True)
   
W języku Python

     SQL_STMT = "SELECT [Category].[Name], [Category].[ID], [Product].[Name], [Product].[ID] \
         FROM [Category], [Product] WHERE [Product].[CategoryID] = [Category].[ID] \
         ORDER BY [Category].[Name], [Product].[Name]"
     tree = dlg.Controls('myTreeControl')
     root = tree.CreateRoot('By Product category')
     db = CreateScriptService('SFDatabases.Database', '/home/.../mydatabase.odb')
     sub_tree = db.GetRows(SQL_STMT)
     tree.AddSubTree(root, sub_tree, withdatavalue=True)
   

CreateRoot

Returns a new root node of the tree control, as a node UNO object of type com.sun.star.awt.tree.XMutableTreeNode. The new tree root is inserted below pre-existing root nodes. Refer to XMutableTreeNode in Application Programming Interface (API) documentation for detailed information.

This method may be called before displaying the dialog box to build the initial tree. It may also be called from a dialog or control event to complete the tree dynamically.

Składnia:

svc.CreateRoot(displayvalue: str, opt datavalue: any): uno

Parametry:

displayvalue: The text appearing in the tree control box.

datavalue: Any value associated with the new node. datavalue may be a string, a number or a date. Omit the argument when not applicable.

Przykład:

W języku Basic

      Dim myTree As Object, myNode As Object
      Set myTree = myDialog.Controls("myTreeControl")
      Set myNode = myTree.CreateRoot("Tree starts here ...")
   
W języku Python

     tree = dlg.Controls('myTreeControl')
     node = tree.CreateRoot('Tree starts here ...')
   

FindNode

Traverses the tree and finds recursively, starting from the root, a node meeting some criteria. Either - 1 match is enough - having its display value matching displayvalue pattern or having its data value equal to datavalue. The comparisons may be or not case-sensitive. The first matching occurrence is returned as a node UNO object of type com.sun.star.awt.tree.XMutableTreeNode. Refer to XMutableTreeNode in Application Programming Interface (API) documentation for detailed information.

When not found, the method returns Nothing, to be tested with the IsNull() builtin function.

This method may be called before displaying the dialog box to build the initial tree. It may also be called from a dialog or control event.

Składnia:

svc.FindNode(displayvalue: str = '', opt datavalue: any, casesensitive = False): uno

Parametry:

One argument out of displayvalue or datavalue must be specified. If both present, one match is sufficient to select the node.

displayvalue: The pattern to be matched. Refer to SF_String.IsLike() method for the list of possible wildcards. When equal to the zero-length string (default), this display value is not searched for.

datavalue: Any value associated with the new node. datavalue may be a string, a number or a date. Omit the argument when not applicable.

casesensitive: Default value is False

Przykład:

W języku Basic

      Dim myTree As Object, myNode As Object
      Set myTree = myDialog.Controls("myTreeControl")
      Set myNode = myTree.FindNode("*Sophie*", CaseSensitive := True)
   
W języku Python

     tree = dlg.Controls('myTreeControl')
     node = FindNode('*Sophie*', casesensitive=True)
     if node is None:
         # ...
   

SetFocus

Set the focus on the control. Return True if focusing was successful.

This method is often called from a dialog or control event.

Składnia:

svc.SetFocus(): bool

Przykład:

W języku Basic

      Dim oControl As Object
      Set oDlg = CreateScriptService("SFDialogs.Dialog",,, "myDialog")
      Set oControl = oDlg.Controls("thisControl")
      oControl.SetFocus()
    
W języku Python

      dlg = CreateScriptService('Dialog', None, None, 'myDialog')
      ctrl = dlg.Controls('thisControl')
      ctrl.SetFocus()
    

SetTableData

Fills a TableControl with the given data. All preexisting data is cleared before inserting the new data passed as argument.

When the TableControl is added to the dialog, it is possible to use the Basic IDE to define whether column and row headers will be shown in the table. If the TableControl has column and/or row headers, the first column and/or row in the provided data array are used as labels for the table headers.

This method returns True when successful.

Składnia:

svc.SetTableData(dataarray: any[0..*, 0..*], widths: int[0..*], alignments: str): bool

Parametry:

dataarray: Data to be entered into the table represented as an Array of Arrays in Basic or a tuple of tuples in Python. The data must include column and row headers if they are to be displayed by the TableControl.

widths: Array containing the relative widths of each column. In other words, widths = Array(1, 2) means that the second column is twice as wide as the first one. If the number of values in the array is smaller than the number of columns in the table, then the last value in the array is used to define the width of the remaining columns.

alignments: Defines the alignment in each column as a string in which each character can be "L" (Left), "C" (Center), "R" (Right) or " " (whitespace, default, meaning left for strings and right for numeric values). If the length of the string is shorter than the number of columns in the table, then the last character in the string is used to define the alignment of the remaining columns.

Przykład:

W języku Basic

The following example assumes that the dialog myDialog has a TableControl named Grid1 with "Show row header" and "Show column header" properties set to "Yes".


     Dim myDialog As Object, oTable As Object, tableData As Variant
     myDialog = CreateScriptService("Dialog", "GlobalScope", "Standard", "myDialog")
     oTable = myDialog.Controls("Grid1")
     tableData = Array("Column A", "Column B", "Column C")
     tableData = SF_Array.AppendRow(tableData, Array("Row 1", 1, 2))
     tableData = SF_Array.AppendRow(tableData, Array("Row 2", 3, 4))
     tableData = SF_Array.AppendRow(tableData, Array("Row 3", 5, 6))
     vAlignments = "LCC"
     vWidths = Array(2, 1, 1)
     oTable.SetTableData(tableData, vWidths, vAlignments)
     myDialog.Execute()
   

The Value property returns the selected row in the table. If no row is selected, an empty Array object is returned. The following code snippet shows how to test if any row is selected in the table.


     rowValues = oTable.Value
     If UBound(rowValues) < 0 Then
         MsgBox "No row selected."
     Else
         MsgBox "Row " & oTable.ListIndex & " is selected."
     End If
   
W języku Python

     dlg = CreateScriptService("Dialog", "GlobalScope", "Standard", "myDialog")
     table_control = dlg.Controls("Grid1")
     table_data = (("Column A", "Column B", "Column C"),
                   ("Row 1", 1, 2),
                   ("Row 2", 3, 4),
                   ("Row 3", 5, 6))
     alignments = "LCC"
     widths = (100, 50, 50)
     table_control.SetTableData(table_data, widths, alignments)
     dlg.Execute()
   

     bas = CreateScriptService("Basic")
     row_values = table_control.Value
     if len(row_values) == 0:
         bas.MsgBox("No row selected.")
     else:
         bas.MsgBox(f"Row {table_control.ListIndex} is selected.")
   

WriteLine

Add a new line at the end of a multiline text field. A newline character will be inserted when appropriate. The method returns True when successful.

An error is raised if the actual control is not of the type TextField or is not multiline.

Składnia:

svc.WriteLine(opt line: str): bool

Parametry:

Line: The string to insert. Default is an empty line.

Przykład:

W języku Basic

      Dim oDlg As Object, oControl As Object
      Set oDlg = CreateScriptService("SFDialogs.Dialog",,, "myDialog")
      Set oControl = oDlg.Controls("thisControl")
      oControl.WriteLine("a new line")
   
W języku Python

     dlg = CreateScriptService('SFDialogs.Dialog', None, None, 'myDialog')
     ctrl = dlg.Controls('thisControl')
     ctr.WriteLine("a new line")
   
warning

Wszystkie podstawowe procedury lub identyfikatory ScriptForge poprzedzone znakiem podkreślenia „_” są zarezerwowane do użytku wewnętrznego. Nie należy ich używać w makrach Basic ani skryptach Pythona.