Nominate our 2022 Qt Champions!

Looping thru QTreeWidget items extremly slow

  • Hello,
    As i found nothing with a quick google research i'm posting my problem here. I have a QTreeWidget. Now i have to add to a child item to a top level item. So first, i go into the treewidget and search my toplevelitem. But here comes the problem: Searching the right item takes a lot of time...
    My first approach was:
    for(int i = 0; i < ui->treeWidget->topLevelItemCount(); i++){.......

    This took around 10ms (the treewidget has ~50 top level items).

    then i managed it to reduce the search time to 5 ms with:
    QList<QTreeWidgetItem *> lss= ui->pluginsw->findItems(name ,Qt::MatchExactly);

    but i think that 5ms are still extremly slow, and still makes my ui lag heavily.

    Do you have any suggestions?

  • Moderators

    Unleass you're doing a lot of these finds I don't see how 5ms could lag your ui? It's 1/200 of a second and a typical desktop monitor ticks at 60Hz.
    Anyway, one thing you could do is to switch to QTreeView and a custom model. That way you could tweak the search on the model class however you needed.

  • Looping is not slow, what takes time is string comparison, cause you basically do brute force string searching.
    As Chris mentioned in normal circumstances this can't lag your GUI.

    But if you fill your tree with huge number of data there might be a few performance problems.
    Possible solutions:

    a) QTreeView with custom model may be faster for multiple reasons including no need for frequent memory allocation and reduced data duplication.

    b) Consider using additional data structure ( temporary or permanent) to speed up large modifications. Example will be usage of hash table which will speed up your search. But keep in mind that maintenance of such data structure may actually make it even slower depending on your usage case.

Log in to reply