View Full Version : QTreeWidget: How to highlight a QTreeWidgetItem?

8th January 2016, 04:59

with Qt 5.5 on Windows 7 in a QTreeWiget I like to highlight a QTreeWidgetItem. (With "highlight" it's meant to be marked with the same colour as by clicking with the mouse on it (light blue color filled rectangle in Windows 7). But with the following code I only get an item marked with a light grey color filled rectangle:

With Qt-Designer in a QWidget I placed a QTreeWidget (ui->treeWidget) with the settings:

"selectionMode = SingleSelection"
"selectionBehavior = SelectRows".

In the constructor of the QWidget I set


Then added only top level "QTreeWigetItems":

QTreeWidgetItem * item = new QTreeWidgetItem(ui->treeWidget);
item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); // Added this line later but it makes no difference
item->setText(0, "Item1");
item->setText(1, "Item2");

Now I like to highlight an item in ui->treeWidget. Result = First item is marked in grey color filled rectangle:


Same here if searching for an item. Result = Searched item is found but marked again with grey color filled rectangle:

QString searchItem = "exampleItem";
QList<QTreeWidgetItem *> itemList = ui->treeWidget->findItems(searchItem, Qt::MatchStartsWith, 4);
if (itemList.size() > 0)

(If I mouse click on the scrollbar of ui->treeWidget the grey marked item is highlighted (with both above codes). Is this a focus problem?)

How to highlight a QTreeWidgetItem?

Added after 14 minutes:

It was a focus problem.

I suppose the QTreeWidget lost its focus because in the QWidget it is placed with many QCheckBoxes next to it. Maybe they were stealing its focus. After placing ui->treeWidget->setFocus() in the last line the item is highlighted correctly.