Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If-else condition in loop: future iterations overwrite results of previous iterations

Tags:

c++

qt

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.

like image 216
user3405291 Avatar asked May 22 '19 08:05

user3405291


1 Answers

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.

like image 53
Christoph Dethloff Avatar answered Sep 19 '22 18:09

Christoph Dethloff