PDA

View Full Version : QTreeView how to abstract only second level hierarchy elements to populate the view



TodorBalabanski
28th November 2017, 12:02
Hello,
I have been working on a task where I should make a drop-down menu like a combo box. I want to set a QMenu to QPushbutton, which should contain a qtreeview. Let's assume we have the following QAbstractItemModel:
X
-->Leaf_B1
.....-->Leaf_B1.1
.....-->Leaf_B1.2
......... ------>Leaf_A1.1.1
-->Leaf_B2
.....-->Leaf_B2.1
......... ------->Leaf_B2.1.1
-->Leaf_B3
.....-->Leaf_B3.1
.....-->Leaf_B3.2
......... ------->Leaf_B2.1.1

I want to customize a QTreeView to look like QListView and to populate only second hierarchy elements in the view (Leaf_B1, Leaf_B2, Leaf_B3).

I have made a search about it on the web and I have stumble across the following article:
https://stackoverflow.com/questions/7563512/how-to-use-qsortfilterproxymodel-to-filter-a-tree-model-that-only-display-childr
http://lynxline.com/jongling-qt-models/

I have tried to use QTreeView::setRootIndex() but without success.

I cannot understand how exactly i can abstract only the second level hierarchy elements.

Does anyone have an idea how can I abstract only these elements and populate them in the view?

Any suggestions are highly appreciated!

Thanks in advance

Ginsengelf
28th November 2017, 13:35
Hi, why don't you simply use a QListView if it does what you want?

Ginsengelf

TodorBalabanski
28th November 2017, 15:19
Because I want to filter out only the second hierarchy elements and this is not possible with QListView as far as I know.

d_stranz
28th November 2017, 21:53
Because I want to filter out only the second hierarchy elements

You basically want a QSortFilterProxyModel that implements the QSortFilterProxyModel::filterAcceptsRow() method. In this method, you will examine the QModelIndex that is passed in, determine whether it is a second-level item or not, and return the proper true or false value. You set the proxy model as the model to be used in the QListView, and set your tree model as source for the proxy model.

You must be careful though, because for tree-structured models traversal down into the tree stops with the first index where the filterAcceptsRow() method returns false. So if you answer "false" for your "X" node, that ends the traversal of the tree. See "Filtering" in the QSortFilterProxyModel documentation.

If this doesn't work for you, then you might be forced to implement a separate model based on your underlying data that contains only the second-level items and use that instead of the tree model as the source model for your list view.