pythoncomboboxlibreoffice-calc

How to fill a ComboBox (in Libre Office Calc) with a python script?


I work on a Calc file, with several tabs. Some are used to store datas (like SQL tables).

With a python macro, I want to fill a ComboBox "Classes" using the datas in one of these tables.

enter image description here

My code :

bas = CreateScriptService('SFDocuments.Document')
formulaire = bas.Forms(F_sheetName, 'Formulaire')
comboBoxClasses = formulaire.Controls(O_classes)

I'd like to be able to do something like this :

comboBoxClasses.addItem("class1")
comboBoxClasses.addItem("class2")

The function addItem does not exist. What should I use instead ?


Solution

  • The code you've shown uses the ScriptForge library. To me, that seems unnecessarily difficult.

    With plain python-uno, you can use an introspection tool such as MRI to view properties, like an improved dir(). MRI shows a method called insertItemText() that takes two arguments, the position and text.

    sheet = XSCRIPTCONTEXT.getDocument().getSheets().getByIndex(0)
    form = sheet.getDrawPage().getForms().getByName("Formulaire")
    comboBoxClasses = form.getByName("ComboBoxClasses")
    comboBoxClasses.insertItemText(0, "History")
    

    If your code already depends heavily on ScriptForge, then you could back out into the ordinary UNO world like this:

    from scriptforge import CreateScriptService
    bas = CreateScriptService('SFDocuments.Document')
    formulaire = bas.Forms('Sheet1', 'Formulaire')
    comboBoxClasses_SF = formulaire.Controls('ComboBoxClasses')
    comboBoxClasses = comboBoxClasses_SF.XControlModel
    comboBoxClasses.insertItemText(1, "Science")
    

    Otherwise, if you really want to learn how to use ScriptForge, here is the documentation I found for form controls: https://help.libreoffice.org/latest/en-US/text/sbasic/shared/03/sf_formcontrol.html, but it doesn't show how to insert items. I'm not sure if there is a way to investigate properties — MRI will not work on the library.