2024-09-29 19:26:23 发布
网友
我正在编写一个小程序,它使用qt5qml作为GUI层,Python3-PyQt5来实现数据模型。在
现在我想在QML中显示一个ComboBox,并将其模型设置为枚举列表。如何将枚举导出为python类的属性,以便在QML中引用它?在
ComboBox
我最好用QML写下:
ComboBox { model: mymodel.car_manufacturers onCurrentIndexChanged: mymodel.selected_manufacturer = currentIndex }
这是我的解决方案,对我来说效果很好。 在python代码中,我有以下内容:
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()
在QML中我有:
您应该将枚举放在从QObject派生的类中。它还应该标记为Q_ENUMS宏。然后,您可以从类的元对象中获取枚举的QMetaEnum,遍历键及其值,并将每个键添加到QStringList中。在
QObject
Q_ENUMS
QMetaEnum
QStringList
MyClass myObj; const QMetaObject* metaObj = myObj.metaObject(); QMetaEnum enumType = metaObj->enumerator(metaObj->indexOfEnumerator("MyEnumType")); QStringList list; for(int i=0; i < enumType.keyCount(); ++i) { QString item = QString::fromLatin1(enumType.key(i)) + " " + QString::number(enumType.value(i)); list.append(item); }
现在可以使用QQmlContext::setContextProperty将字符串列表公开给QML:
QQmlContext::setContextProperty
当ComboBox项如下所示时,将有一个包含枚举键和值的组合框:
ComboBox { model: myModel ... }
这是我的解决方案,对我来说效果很好。 在python代码中,我有以下内容:
在QML中我有:
^{pr2}$您应该将枚举放在从
在C++中,它会像:QObject
派生的类中。它还应该标记为Q_ENUMS
宏。然后,您可以从类的元对象中获取枚举的QMetaEnum
,遍历键及其值,并将每个键添加到QStringList
中。在现在可以使用
^{pr2}$QQmlContext::setContextProperty
将字符串列表公开给QML:当
ComboBox
项如下所示时,将有一个包含枚举键和值的组合框:相关问题 更多 >
编程相关推荐