1 回答
TA贡献1805条经验 获得超10个赞
首先,QML Item Combobox 不是 QtWidgets QComboBox,因此您不应该使用该类进行过滤,这就是您的尝试失败的原因。从 python(或 C++)访问 QML 元素也是不好的做法,因为生命周期不受管理(例如,可以删除并重新创建相同“id”的对象而不通知),相反,您必须创建允许交换信息的 QObject ,例如对于 QComboBox,您可以创建一个模型:
main.py
import os
import sys
# qt imports
from PyQt5.QtCore import pyqtProperty, pyqtSlot, QObject, QUrl
from PyQt5.QtGui import QGuiApplication, QStandardItem, QStandardItemModel
from PyQt5.QtQml import QQmlApplicationEngine
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class Manager(QObject):
def __init__(self, parent=None):
super().__init__(parent)
self._model = QStandardItemModel()
@pyqtProperty(QObject, constant=True)
def model(self):
return self._model
@pyqtSlot()
def foo(self):
print("clicked")
def main():
app = QGuiApplication(sys.argv)
manager = Manager()
engine = QQmlApplicationEngine()
engine.rootContext().setContextProperty("manager", manager)
filename = os.path.join(CURRENT_DIR, "main.qml")
engine.load(QUrl.fromLocalFile(filename))
item = QStandardItem("a")
manager.model.appendRow(item)
sys.exit(app.exec_())
if __name__ == "__main__":
main()
主.qml
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
visible:true
width:600
height:400
Button {
id: clickMe
x: 244
y: 263
text: qsTr("click me!")
onClicked: manager.foo()
}
ComboBox {
id: comboBox
x: 199
y: 157
width: 200
model: manager.model
textRole: "display"
}
}
添加回答
举报