I have a model that retrieves data from a table in a database from a certain SQL query, and shows the items in a QTreeView. The characteristics are:
- the data comes from a table, but has an underlying tree structure (some rows are parents that have rows below them as children)
- this tree structure is shown in the QTreeView
- the children are selectable in the QTreeView (not so the parents)
- the table in the database gets updated continuously
- in the updates, a children can be added to any existing parent
- periodically (with a QTimer) the QTreeView is updated with the contents of the table
Since the children are added at any time to any parent, the first silly approach when updating the QTreeView is clearing it all, and append all the rows again, in form of parent or children, to the QTreeView. This is a 0-order approximation, and it is indeed terrible inefficient. In particular, the following problems appear:
- Any existing selection is gone
- Any expanded parent showing its children is collapsed (unless ExpandAll is active)
- The view is reset to show the very first row.
What is the best solution to this problem? I mean, the first solution I will try will be not to clear the QTreeView, but instead parse all the returned rows from the table, and check for each of them whether the corresponding item in the QTreeView exists, and add it if not. But I wonder if there is a trickiest solution to engage a given table in a database with a QTreeView (I know this exists for a QTableView, but then the tree structure is gone).
beginInsertRows
andendInsertRows
, the tree view selection and nodes state will be preserved as it was before updating the tree. – vahancho