我可以尝试使用Python中的Qt和QML。
main_window.qml:
import QtQuick 2.10
Rectangle {
id: mainWindow
objectName: "mainWindow"
width: 1000
height: 100
x: 100
y: 100
color: "gray"
Rectangle {
id: red
objectName: "red"
width: 800
height: 50
x: 200
y: 200
color: "red"
}
}
rectangle.qml:
import QtQuick 2.10
Rectangle {
id: green
objectName: "green"
width: 800
height: 50
x: 200
y: 400
color: "green"
}
test.py:
import os
import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlComponent
from PyQt5.QtQuick import QQuickView
os.environ["QML_DISABLE_DISK_CACHE"] = "true"
class Graphic:
def __init__(self):
self.main_window = QQuickView()
self.main_window.setSource(QUrl.fromLocalFile("ui/main_window.qml"))
def load_screen(self):
component = QQmlComponent(self.main_window.engine())
component.loadUrl(QUrl.fromLocalFile("ui/rectangle.qml"))
item = component.create()
item.setParent(self.main_window.rootObject())
self.main_window.show()
if __name__ == '__main__':
app = QGuiApplication(sys.argv)
graphic = Graphic()
graphic.load_screen()
app.exec()
这是我的问题的一个简单例子。 我尝试在主窗口中动态加载和显示屏幕。 我看到灰色和红色的矩形,但看不到绿色的矩形。 怎么了?
答案 0 :(得分:0)
根据docs:
parent:QQuickItem *
此属性包含项目的可视父级。
注意:视觉父母的概念不同于 QObject父级。项目的视觉父母可能不一定是 与其对象父级相同。请参阅概念 - Qt Quick中的Visual Parent 了解更多详情。
换句话说,要使项目可见,必须通过setParentItem()
建立视觉父项:
def load_screen(self):
component = QQmlComponent(self.main_window.engine())
component.loadUrl(QUrl.fromLocalFile("ui/rectangle.qml"))
item = component.create()
item.setParent(self.main_window.rootObject())
item.setParentItem(self.main_window.rootObject()) # <---
self.main_window.show()