Reputation: 31
I have a tree widget that I'm using for a user/room concept. How can I style the rooms independently from the users in the rooms? I'm assuming it has something to do with QT's property selector in CSS? I would like to be able to do this:
QTreeView::item[isUser="true"] { background: blue; }
QTreeView::item[isRoom="true"] { background: red; }
Upvotes: 3
Views: 4032
Reputation: 19
I was able to accomplish what I needed by creating a label, using the setProperty
method on that label, and then using the setItemWidget
function to attach that QLabel to the appropriate QTreeWidgetItem. So I wouldn't be "styling the QTreeWidgetItem", but rather styling the QLabel that was overlayed on top of the QTreeWidgetItem. The following example sets my topLevelItem in the QTreeWidget to be ready to be styled as a room:
QTreeWidgetItem *topItem = ui->treeWidget->topLevelItem(0);
currentLabel = new QLabel;
currentLabel->setProperty("room",true);
currentLabel->setText(QString("Room Lobby"));
ui->treeWidget->setItemWidget(topItem,0,currentLabel);`
I can then select it in the stylesheet with
QLabel[room="true"] { background: red; }
Upvotes: 1
Reputation: 4954
Since the items in a model are not QObjects (nor QWidgets), you will not be able to add a property to the item, or style them with stylesheets.
I have two suggestions for doing what you want to do :
1) (C++ only) Attach your QTreeView
to a QStandardItemModel
, and when you add items as QStandardItem
objects, you can call QStandardItem::setBackground()
with either Qt::blue
or Qt::red
depending of whether the item is a room or a user.
2) (C++ and CSS) Define a QStyledItemDelegate
that you attach to your QTreeView
. In your reimplementation of QStyledItemDelegate::paint()
method, use a QLabel
to display the content of the item, then set a property on that QLabel
. You will then be able to use a stylesheet to customize the look of the label :
QLabel[isUser="true"] { background: blue; }
QLabel[isRoom="true"] { background: red; }
Upvotes: 3