gpt4 book ai didi

python - PySide2 加载和创建组件时发生了什么?

转载 作者:太空宇宙 更新时间:2023-11-03 21:24:44 25 4
gpt4 key购买 nike

这个例子正在运行:

from PySide2.QtCore import QUrl
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlComponent
from PySide2.QtQuick import QQuickView

app = QGuiApplication()
view = QQuickView()
engine = view.engine()
url = QUrl("main.qml")
view.setSource(url)
component = QQmlComponent(engine, QUrl.fromLocalFile("block.qml"))
item = component.create()
item.setParent(view.rootObject())
item.setParentItem(view.rootObject())
view.show()
app.exec_()

该项目是 QQuickItem 的类。component.create()是QQuickItem的一个类。将此示例更改为:

from PySide2.QtCore import QUrl
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlComponent
from PySide2.QtQuick import QQuickView

app = QGuiApplication()
view = QQuickView()
engine = view.engine()
url = QUrl("main.qml")
view.setSource(url)
item = QQmlComponent(engine, QUrl.fromLocalFile("block.qml")).create()
item.setParent(view.rootObject())
item.setParentItem(view.rootObject())
view.show()
app.exec_()

抛出异常:

Traceback (most recent call last):
File "/home/babywolf/dev/apps/qttest/test.py", line 14, in <module>
item.setParent(view.rootObject())
RuntimeError: Internal C++ object (PySide2.QtQuick.QQuickItem) already deleted.
Process finished with exit code 1

出了什么问题?

main.qml:

import QtQuick 2.0

Rectangle {
width: 200
height: 200
color: "green"
}

block .qml:

import QtQuick 2.0

Text {
text: "Hello World"
anchors.centerIn: parent
}

最佳答案

这是 PySide 的一种特殊行为,如果变量未分配给对象,它将被消除,因此在这种情况下,QQmlComponent 被创建但未分配给变量,因此与第一种情况不同,它将被删除,因为它被分配给变量组件,因此当想要创建该项目时,该组件不再存在并生成该错误。

一种解决方案是传递父级,因为在本例中可以查看延长其生命周期:

item = QQmlComponent(engine, QUrl.fromLocalFile("block.qml"), view).create()
# └----- parent

关于python - PySide2 加载和创建组件时发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53932623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com