Search code examples
pythonqtqmlqt-quick

I want to set a Qt QML Combobox to a PyQt5 object property


I am writing a small program which uses Qt5 QML as the GUI layer and Python3-PyQt5 to implement the data model.

I now want to display a ComboBox in QML and set its model to a list of enums. How would I export the enum as a property of the python class so that I can reference it in QML?

Preferably I would write this in QML:

ComboBox {
  model: mymodel.car_manufacturers
  onCurrentIndexChanged: mymodel.selected_manufacturer = currentIndex
}

Solution

  • Here is my solution which works good enough for me. In the python code I have the following:

    class CarManufacturers(enum.Enum):
        BMW, Mercedes = range(2)
    
    mfcChanged = pyqtSignal()
    
    @pyqtProperty('QStringList', constant=True)
    def carmanufacturers(self):
        return [mfc.name for mfc in CarManufacturers]
    
    @pyqtProperty('QString', notify=mfcChanged)
    def mfc(self):
        return str(CarManufacturers[self._mfc].value)
    
    @modus.setter
    def mfc(self, mfc):
        print('mfc changed to %s' % mfc)
        if self._mfc != CarManufacturers(int(mfc)).name:
            self._mfc = CarManufacturers(int(mfc)).name
            self.mfcChanged.emit()
    

    and in the QML I have:

    ComboBox {
        model: myModel.carmanufacturers
        currentIndex: myModel.mfc
        onCurrentIndexChanged: myModel.mfc = currentIndex
    }