1

I have a little problem I am trying to figure out, I am working on a QT app that is using the QTreeView and I have a bunch of categories which have children, so they look like

Parent 1
Parent 2
  - Child 1
  - Child 2
Parent 3

and so on and so forth, so in my database I have rows which have all the regular details (name, id, date created, etc) and the ones which are children have their parent specified (so pid=parent row id). I then loop over then using the standard QSqlQuery stuff. But the problem I am running into is this...

Items are added to the treeview by QStandardItem* item = new QStandardItem(icon, name); and then appending the row model->appendRow(item); but my children need to call parentitem->appendRow(item); so the QStandardItem* item of the parent. But how can I find out what that is without storing every single item?

Moral of the story is, is there a way to do one of the following that won't destroy performance.

  1. Store the QStandardItem* item in an array that I could reference the parent in the childs loop?
  2. Assign an ID or something to QStandardItem* item which I could then reference when adding a child.
  3. Generate a TreeView model from an array, where the children array elements get added as children?
  4. Something else I haven't thought of...

I can't seem to find any good examples of QTreeView with children from a database.

4

1 回答 1

0

您只需要一个QMap<int, QStandardItem*> rowItemMap. 当您从数据库中检索具有给定行 ID 的行时,您会立即创建一个项目并将其添加到地图中。然后,您将其添加到您在地图中查找的父级。您需要创建一个虚拟父项作为根项。存储指向项目的指针没有任何问题。对于合理数量的物品,这无关紧要。如果您考虑存储超过 10k 项,您可能需要考虑使用一个视图,该视图在树的某个深度提供传递闭包。然后将这样的视图通过 直接映射到树上会容易得多QSqlTableModel,而无需将整个树从数据库复制到临时模型中。

于 2013-09-13T02:49:51.453 回答