无法在Python中显示TreeView

问题描述 投票:0回答:1

[尝试在Python中为Qt测试一个非常简单的TreeView控件,但是由于某些原因,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

python qml pyside2
1个回答
0
投票

问题在于,由于未将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)
# ...
© www.soinside.com 2019 - 2024. All rights reserved.