Iterating through QTreeWidget Nodes

Will Kraft picture Will Kraft · Jan 7, 2012 · Viewed 10.6k times · Source

As I posted several times over the past few months, I'm writing a journal/diary application in Qt. Entries are sorted in a QTreeWidget by year, month, day, and entry (default config that sorts entries by day) or by year, month, and entry (where all entries from the same month are grouped together)

The entry nodes have two columns: The first one is visible and holds the entry name. The second column is invisible and holds the row number of the corresponding entry in the database. When that entry is selected, the program does a select query based on that row number and displays the content. Root, year, month, (and day, if enabled) nodes also have a second column but the row number on those is always -1. (valid row count starts at 0)

The journal toolbar already has back and forward buttons that lets the user view the next and previous entries. While this function already works, the current selected item in the tree doesn't change with it, and that's what I’m trying to fix.

I've decided that the best way to do this is a loop function that scans the second hidden column values of each until the correct row number is found. Each click of the back/forward buttons will call this function again so the selected node will always match the current entry being viewed once I get this working.

The drawback is that this method can be slow if the database gets huge, but there's not much I can do about that. The user may delete entries or shuffle them around, so simply relying on rownumber++ or rownumber-- could cause problems. Since the database doesn't fill in missing row numbers but just goes on to the next one, there could be problems if the program always assumes that every row ever made in the database still exists at any given time.

My question is how do I scan a particular column of every node in a QTreeWidget?

Answer

Daniel Vérité picture Daniel Vérité · Jan 8, 2012

Iterating through all items can be done with:

QTreeWidgetItemIterator it(treewidget);
while (*it) {
  if ((*it)->text(column_number)=="searched")
    break;
  ++it;
}

but maybe QTreeWiget::findItems() is just what you need.

Also look at QStandardItem::data(), it's a better way of storing per-item hidden data, compared to a hidden column.