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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With