Hide children of QStandardItem in QTreeView
I feel like I'm missing something really obvious, but is it possible to disable expansion of a particular QStandardItem within a QTreeView when it has children? My model has 4 root items uniquely subclassed from QStandardItem, each with a set of children of unknown quantity, but I only want two of them to actually show their children. Is this possible?
I think QTreeWidgetItem::ChildIndicatorPolicy is a convenience function that does something like this, but I can't see anything similar in QStandardItem. Where in QStandardItem's implementation does it control the display of its children?
In case it's relevant, I'm displaying them in a QTreeView.
Re: Hide children of QStandardItem in QTreeView
if you have your own implementation of QAbstractItemModel or QStandardItemModel for your QTreeView you can return 0 from rowCount() for particular items
or override function hasChildren () and returm false for particular items
Re: Hide children of QStandardItem in QTreeView
That is exactly what I was looking for! Thank you.
Here's my code:
Code:
//myitemmodel.h
{
Q_OBJECT
public:
explicit MyItemModel
(QObject *parent
= 0);
explicit MyItemModel
(int rows,
int columns,
QObject* parent
= 0);
virtual bool hasChildren
(const QModelIndex &parent
) const;
};
//myitemmodel.cpp
#include "myitem.h"
MyItemModel
::MyItemModel(QObject *parent
) :{}
MyItemModel
::MyItemModel(int rows,
int columns,
QObject *parent
) :{}
bool MyItemModel
::hasChildren(const QModelIndex &parent
) const {
if(itemFromIndex(parent) != 0)
{
switch(itemFromIndex(parent)->type())
{
case MyItem::CUSTOMTYPE1: //QStandardItem::UserType +1
case MyItem::CUSTOMTYPE3: //QStandardItem::UserType +3
case MyItem::CUSTOMTYPE4: //QStandardItem::UserType +4
/* force children to be hidden, no matter the view type */
return false;
case MyItem::CUSTOMTYPE2: //QStandardItem::UserType +2
default:
/* proceed normally */
break;
}
}
}
int SessionItemModel
::rowCount(const QModelIndex &parent
) const {
if(itemFromIndex(parent) != 0)
{
switch(itemFromIndex(parent)->type())
{
case MyItem::CUSTOMTYPE1: //QStandardItem::UserType +1
case MyItem::CUSTOMTYPE3: //QStandardItem::UserType +3
case MyItem::CUSTOMTYPE4: //QStandardItem::UserType +4
/* force children to be hidden, no matter the view type */
return 0;
case MyItem::CUSTOMTYPE2: //QStandardItem::UserType +2
default:
/* proceed normally */
break;
}
}
}
This had the desired effect of particular item types appearing as if they had no children in my QTreeView. Note that only overriding QStandardItemModel::rowCount() made it so that the expansion button still appeared in the QTreeView even though its children were hidden, so I had to override QStandardItemModel::hasChildren(), too. It seems that overriding rowCount is optional in my case, but I did it anyway to be safe.