PDA

View Full Version : Treeview - preselect node before displaying



JD2000
26th November 2009, 19:05
I have a tree, populated from an SQL database with

model = new QSqlQueryModel(this);
model->setQuery("SELECT * FROM people ORDER BY Name");
model->setHeaderData(0, Qt::Horizontal, tr("ID"));
model->setHeaderData(1, Qt::Horizontal, tr("Name"));

TreeView->setModel(model);
TreeView->show();

The 'ID' is the primary key of the 'people' table in the database.

My question is how do I show the tree with a given 'ID' / record already selected?

eg after a new record has been inserted into the table and its 'ID' retreived with something like
query.lastInsertId().toString();

JD2000
30th November 2009, 14:26
After much trial and error I've come up with a solution:

With a known ID


model->setQuery("SELECT * FROM people ORDER BY Name");
int maxrows = model->rowCount(QModelIndex());
int row = 0;
while(row++ <= maxrows)
if(ID == model->data(model->index(row, 0)).toInt())
TreeView->selectionModel()->setCurrentIndex(model->index(row, 1),
QItemSelectionModel::SelectCurrent);

will rebuild the tree, find the relevant ID / record in column 0 and set the corresponding name (in column 1) as the current selection. A currentChanged() signal in then emitted, resulting in a tree update.

not very efficient, if anyone knows of a better way, I would be interested to know.