Last in a series on treebuilding in PySide: see Table of Contents.
As mentioned in post IIC, if our ultimate goal were to display a tree as simple as the one in the simpletreemodel, we would probably just use QTreeWidget or QStandardItemModel. In both cases, it is almost embarrassing how much easier it is to create the tree. This is because we don't need to roll our own model or data item classes.
In what follows, we will see how to use QTreeWidget and QStandardItemModel to create and view a read-only tree with multiple columns of data in each row. To keep it simple, we won't load data from a file, and the code only creates a very simple little tree. It would be a useful exercise to expand these examples to exactly mimic the GUI created in simpletreemodel.
While it is often poo-poohed as slow and inflexible, for simple projects QTreeWidget is extremely convenient and easy to use. Simply instantiate an instance of QTreeWidget, populate the tree with QTreeWidgetItem instances, and then call show() on the widget:
This is only slightly more complicated than QTreeWidget. We populate the tree with lists of QStandardItems. To add a child to a row, we apply appendRow() to the first element (i.e., the first column) of the parent row:
While a tad more complicated than using QTreeWidget, this is still drastically simpler than subclassing QAbstractItemModel.
As is usually the case, there are many ways to get to the same destination. The route you take will depend on your goals, the complexity of your data, how much time you have to write your code, and how fast you want the program to be. As mentioned before, it would be overkill to subclass QAbstractItemModel for a data store as simple as the one in simpletreemodel. This post shows just how easy it would be to create the exact same tree with an order of magnitude less code.
Those that have read any of these posts, thanks for reading! I'll be putting a PDF of all the posts together so you don't have to fight through a maze of posts for all the information.