我不会从 python 动态创建元素,我只是想访问 qml 文件中已声明的现有元素。
我使用 findChild 来获取 QObject 引用并连接到信号。这工作正常,但是当我尝试更具体并获取像 QComboBox 这样的小部件(不是 QObject)时,我总是得到 None。我是否遗漏了一些东西或者 findChild 不适合与小部件一起使用?
这是我的简单 qml 代码:
Window {
visible:true
width:600
height:400
Button {
id: clickMe
objectName: "clickMe"
x: 244
y: 263
text: qsTr("click me!")
}
ComboBox {
id: comboBox
objectName: "comboBox"
x: 199
y: 157
width: 200
}
}
这是我的Python代码:
# qt imports
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QMessageBox
from PyQt5.QtWidgets import QComboBox, QPushButton
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QObject
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.load('main.qml')
win = engine.rootObjects()[0]
win.show()
# this does work because it is QObject:
clickMe = win.findChild(QObject, "clickMe")
clickMe.clicked.connect(Foo)
# this does not work, I get None so can't add items to the combobox:
comboBox = win.findChild(QComboBox, "comboBox")
comboBox.addItem("a")
sys.exit(app.exec_())
holdtom
相关分类