Hi,
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
"ui->treeWidget->setColumnCount(4)";
"ui->treeWidget->setColumnCount(4)";
To copy to clipboard, switch view to plain text mode
Then added only top level "QTreeWigetItems":
item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); // Added this line later but it makes no difference
item->setText(0, "Item1");
item->setText(1, "Item2");
....
ui->treeWidget->addTopLevelItem(item);
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");
....
ui->treeWidget->addTopLevelItem(item);
To copy to clipboard, switch view to plain text mode
Now I like to highlight an item in ui->treeWidget. Result = First item is marked in grey color filled rectangle:
ui->treeWidget->topLevelItem(0)->setSelected(true);
ui->treeWidget->topLevelItem(0)->setSelected(true);
To copy to clipboard, switch view to plain text mode
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)
ui->treeWidget->setCurrentItem(itemList[0]);
QString searchItem = "exampleItem";
QList<QTreeWidgetItem *> itemList = ui->treeWidget->findItems(searchItem, Qt::MatchStartsWith, 4);
if (itemList.size() > 0)
ui->treeWidget->setCurrentItem(itemList[0]);
To copy to clipboard, switch view to plain text mode
(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.
Bookmarks