gpt4 book ai didi

python - 无法在 Python 中显示 TreeView

转载 作者:行者123 更新时间:2023-12-04 10:34:23 25 4
gpt4 key购买 nike

尝试一个非常简单的 TreeView在 Python 中控制 Qt,但由于某种原因,GUI 只是空白。
main.qml

import QtQuick 2.14
import QtQuick.Controls 2.14
import QtQuick.Controls 1.4 as OldControls

ApplicationWindow {
visible: true
title: qsTr("Simple Tree View")

OldControls.TreeView {
anchors.fill: parent
model: simpleModel
OldControls.TableViewColumn {
role: "display"
title: "Name"
width: 100
}
}
}
main.py
import sys
from os.path import abspath, dirname, join

from PySide2.QtGui import QGuiApplication, QStandardItemModel, QStandardItem
from PySide2.QtQml import QQmlApplicationEngine


class SimpleTreeView(QStandardItemModel):
def __init__(self, parent=None):
super().__init__(parent)

self.setColumnCount(1)

root = self.invisibleRootItem()
group1 = QStandardItem("group1")
group1.setText("group1")
value1 = QStandardItem("value1")
value1.setText("value1")
group1.appendRow(value1)
root.appendRow(group1)


if __name__ == '__main__':
app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
qmlFile = join(dirname(__file__), 'main.qml')
engine.rootContext().setContextProperty("simpleModel", SimpleTreeView())
engine.load(abspath(qmlFile))

if not engine.rootObjects():
sys.exit(-1)

sys.exit(app.exec_())

Linux 中的输出

enter image description here

最佳答案

问题是,由于 SimpleTreeView 对象没有分配给变量,所以它被销毁了,可以使用 destroyed 来验证。信号。

class SimpleTreeView(QStandardItemModel):
def __init__(self, parent=None):
super().__init__(parent)

self.destroyed.connect(lambda o : print("destroyed:", o))
# ...

输出:
destroyed: <PySide2.QtCore.QObject(0x56377cf050f0) at 0x7ffa20deac40>

解决办法是给那个对象赋值一个变量,这样生命周期就更长了:
qmlFile = join(dirname(__file__), 'main.qml')
model = SimpleTreeView()
engine.rootContext().setContextProperty("simpleModel", model)
# ...

enter image description here

关于python - 无法在 Python 中显示 TreeView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60257998/

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