将数据与PyQt5 QTreeWidgetItem关联的正确方法是什么

2024-09-30 03:24:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用pyqt5qtreewidget构建一个类似于Macintosh Finder的文件树浏览器。(奇怪的是,似乎没有一个。)

我想将信息与每个QTreeWidgetItem关联起来。这是显示的字符串之外的信息。在

正确的方法是什么?到目前为止,我想出了:

  1. 子类QTreeWidgetItem并添加我自己的实例变量。在
  2. 以某种方式将信息填充到模型中,但我不完全确定如何做到这一点。也许我需要子类QAbstractItemModel?在
  3. 在QTreeWidgetItems和我的附加信息之间创建关联数组?(似乎是个很坏的主意。)

Tags: 文件实例方法字符串模型信息finder方式
1条回答
网友
1楼 · 发布于 2024-09-30 03:24:52
  1. Subclass QTreeWidgetItem and add my own instance variables

根据docs

Subclassing

When subclassing QTreeWidgetItem to provide custom items, it is possible to define new types for them so that they can be distinguished from standard items. The constructors for subclasses that require this feature need to call the base class constructor with a new type value equal to or greater than UserType.

因此,如果您想做一些可维护的事情并希望使用QTreeWidget,因为它允许模块化,那么这个选项是合适的。在

  1. Stuff the information into the model, somehow, but I'm not entirely sure how to do that. Perhaps I need to subclass the QAbstractItemModel?

根据类的定义:QTreeWidget类提供了一个使用预定义树模型的树视图

这意味着类不能放置一个自定义模型,这个特性的优点是它易于使用,因为你不必使用较低级别的元素,缺点是:你不能自定义模型。在

^{4磅}$

您可以通过void QTreeWidgetItem::setData(int column, int role, const QVariant &value)方法添加一些值,并通过QVariant QTreeWidgetItem::data(int column, int role) const恢复这些值。在

如果要向项目添加信息,但不可扩展,建议使用此方法。在

答案是第一个选项,但对于这种类型的任务,我不建议使用QTreeWidget,因为它有不必要的元素,导致内存消耗增加和速度降低,使用QTreeView并创建一个自定义模型是合适的,但是如果您想显示本地文件的信息,那么已经有了实现它的模型:QFileSystemModel。在

示例:

import sys

from PyQt5.QtWidgets import *

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = QTreeView()
    model = QFileSystemModel()
    model.setRootPath("")
    w.setModel(model)
    w.show()
    sys.exit(app.exec_())

相关问题 更多 >

    热门问题