I do not create the elements dynamically from python, I just intend to access existing elements already declared in the qml file.
I use findChild to get a QObject reference and connect to signals. This works fine, but when I try to be more specific and get a widget (not a QObject) like a QComboBox, I always get None. Am I missing something or findChild is not meant to be used with widgets?
This is my simple qml code:
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
}
}
And this is my python code:
# 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_())