how to traverse all the items of QListWidget/QTreeWidget?



  • how to traverse all the items of QListWidget/QTreeWidget?



  • Hi,

    for a QListWidget you can do something like

    // myWidget is a QListWidget*
    for (int i = 0; myWidget->count(); ++i) {
        QListWidgetItem *item = myWidget->item(i);
        // Do something with item
    }
    

    for a QTreeWidget

    // myWidget is a QTreeWidgetItem*
    void traverseNode(QTreeWidgetItem *item) {
        // Do something with item
        for (int i = 0; i < item->childCount(); ++i)
            traverseNode(item->child(i));
    }
    
    for (int i = 0; i < myWidget->topLevelItemCount(); ++i) {
        QTreeWidgetItem *item = myWidget->topLevelItem(i);
        traverseNode(item);
    }
    

    For a tree usually you have to decide to process the item itself before or after its child.



  • @mcosta thank you
    does this->findItems() faster?


  • Moderators

    @opengpu2
    It depends what your intend is. mcosta answered your initial question.
    If you are searching something specific and you know the details anyhow findItems() is the better choices.



  • As @koahnig said, findItems() find items by name.
    If you want to traverse the List/Tree you cannot use it.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.