I try to highlight a selectedItem
and its children among a list of items
.
const QList<Item *> items = /* ... */;
Item *selectedItem = /* ... */;
Q_FOREACH( Item *item, items ) {
if ( selectedItem == item ) {
item->setHighlightEnabled(true); // Highlight selected item
} else {
item->setHighlightEnabled(false); // De-highlight other items
}
}
The item->setHighlightEnabled
method does the same for children recursively:
void Item::setHighlightEnabled(bool enabled)
{
if (enabled) {
/* highlight item */
} else {
/* de-highlight item */
}
// Go through all children and highlight them too
Q_FOREACH (Item *child, children())
child->setHighlightEnabled(enabled);
}
Works fine but there is a bug. We loop over all items. When a parent is selected, parent and its children are highlighted. But then loop continues iterating over children. Since children are NOT selected, therefore they are de-highlighted (overwriting highlight in previous loop iterations). I wonder what is the best practice to fix it.
As far as i understand your problem, you could make to for-loops. In the first one you de-highlight all elements. And the second one you leve as is and just stop it with a break;
statement, once it found the selected item.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With