我想将Qt-QML组合框设置为PyQt5对象属性

2024-09-29 19:26:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个小程序,它使用qt5qml作为GUI层,Python3-PyQt5来实现数据模型。在

现在我想在QML中显示一个ComboBox,并将其模型设置为枚举列表。如何将枚举导出为python类的属性,以便在QML中引用它?在

我最好用QML写下:

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

Tags: 模型程序列表model属性gui数据模型qml
2条回答

这是我的解决方案,对我来说效果很好。 在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中我有:

^{pr2}$

您应该将枚举放在从QObject派生的类中。它还应该标记为Q_ENUMS宏。然后,您可以从类的元对象中获取枚举的QMetaEnum,遍历键及其值,并将每个键添加到QStringList中。在

在C++中,它会像:

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:

^{pr2}$

ComboBox项如下所示时,将有一个包含枚举键和值的组合框:

ComboBox {
  model: myModel
  ...
}

相关问题 更多 >

    热门问题