Issue
I am building a file tree browser with the PyQT5 QTreeWidget similar to the Macintosh Finder. (Strangely, there doesn't seem to be one.)
I want to associate information with each QTreeWidgetItem. This is information beyond the string that is displayed.
What's the correct way to do this? So far I've come up with:
- Subclass QTreeWidgetItem and add my own instance variables.
- Stuff the information into the model, somehow, but I'm not entirely sure how to do that. Perhaps I need to subclass the
QAbstractItemModel
? - Create an associative array between the QTreeWidgetItems and my additional information? (Seems like a very bad idea.)
Solution
- Subclass QTreeWidgetItem and add my own instance variables
According to the 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
.
So this option is appropriate if you want to do something maintainable and want to use QTreeWidget
anyway as it allows to have modularity.
- Stuff the information into the model, somehow, but I'm not entirely sure how to do that. Perhaps I need to subclass the
QAbstractItemModel
?
According to the definition of the class: The QTreeWidget class provides a tree view that uses a predefined tree model
That means that the class can not be placed a custom model, the advantage of this feature is its ease of use since you do not have to use a lower level element, the disadvantage: you can not customize the model.
- Create an associative array between the
QTreeWidgetItems
and my additional information? (Seems like a very bad idea.)
you can add some values through the void QTreeWidgetItem::setData(int column, int role, const QVariant &value)
method, and recover them through QVariant QTreeWidgetItem::data(int column, int role) const
.
This is recommended when you want to add information to the items, but it is not scalable.
The answer would be the first option but for this type of tasks I do not recommend using QTreeWidget
since it has unnecessary elements causing the memory consumption to increase and the speed to decrease, it would be appropriate to use QTreeView
and create a custom model, but if you want to show the information of the local files there is already a model that implements it: QFileSystemModel
.
Example:
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_())
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.