QTreeView - Hide controls for expanding and collapsing specific items
-
Hi,
I have a custom model (derived from QAbstractItemModel) that it is shown with a QTreeView.When an item of the model has children, the QTreeView shows a expanding/collapsing icon (a triangle) that allows you to show/hide the children. I want to hide the icon on an specific item. This item has children so it has to be expanded always. I want to achieve the following style for the tree (I will use the symbols + and - as the expanding/collapsing icon)
A B C D <-I don't want to show the expanding/collapsing icon in this item. -E E1 E2 +F -G -G1 G1.1 G1.2 G2
I have been able to hide the expanding/collapsing icon of the first item (the A) with the following command:
myQTreeView.setRootIsDecorated(false);
However, I don't know how to hide the icon for the item D in my example.
Any ideas?
Thank you.
-
I hope that someone will suggest a simpler solution, because mine would require some work, but:
You could use a custom item delegate (derived from QStyledItemDelegate) and override the paint() and sizeHint() method.
In paint() You draw what You need (icons, text, QTextDocument, etc.) for a specific item. You could use Qt::UserRole to specify the items, that need special drawing like this:
if(index.data(Qt::UserRole).toInt() == 1) { //draw differently } else { //draw standard QStyledItemDelegate::paint(painter, option, index); }
In sizeHint() You declare the size of a single item.
http://doc.qt.io/qt-5/qstyleditemdelegate.html
http://doc.qt.io/qt-5/qtwidgets-itemviews-spinboxdelegate-example.html
I'm using this method for something slightly different, but it should work for You as well.
-
rather than the delegate I'd reimplement QTreeView:
protected:virtual void drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const virtual void drawRow(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
and slots
void collapse(const QModelIndex &index) void expand(const QModelIndex &index)
But agree is not straightforward and will require some work