我目前正在开发一个包含 QML 的 PyQt5 应用程序。该应用程序从配置文件动态生成 QML 代码 (
configuration.yaml
)。然后,生成的 QML 代码使用信号从 Python 发送到 QML,我正在利用 Qt.createQmlObject()
来实例化 QML 对象。
我遇到的挑战是这个过程在主应用程序中无缝运行,但是当在
Popup
元素中尝试相同的操作时,生成的 QML 对象在应用程序界面上不可见。值得注意的是,执行期间不会引发任何错误。尽管通过调试验证QML对象已成功创建,但它们没有出现在界面上。
因为
TestPopup.qml
使用 MainPopup.qml
作为其父级,可能会导致问题。我检查了 addElement()
功能,它工作正常。
代码:
MainPopup.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3
import QtQuick.Controls.Material 2.2
Popup {
id: mainPopup
...
}
TestPopup.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3
import QtQuick.Controls.Material 2.2
MainPopup {
id: testPopup
function addElement(elementId, elementString) {
Qt.createQmlObject(elementString, testPopup, elementId)
}
...
}
app.py
...
test_qml = """
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3
Text {
text: "Hello World!"
anchors.centerIn: parent
}
"""
test_popup = window.findChild(QObject, "testPopup")
test_popup.addElement("testID", test_qml)
...
从那时起,我试图在
testPopup
中添加一个元素,该元素从 MainPopup
延伸出来,并且自己不可见。我必须将新元素添加到 MainPopup
的 contentItem
,如下所示:
...
function addElement(elementId, elementString) {
Qt.createQmlObject(elementString, testPopup.contentItem, elementId)
}
...