Results 1 to 2 of 2

Thread: Treeview - preselect node before displaying

  1. #1
    Join Date
    Oct 2009
    Posts
    151
    Thanks
    6
    Thanked 13 Times in 11 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default Treeview - preselect node before displaying

    I have a tree, populated from an SQL database with
    Qt Code:
    1. model = new QSqlQueryModel(this);
    2. model->setQuery("SELECT * FROM people ORDER BY Name");
    3. model->setHeaderData(0, Qt::Horizontal, tr("ID"));
    4. model->setHeaderData(1, Qt::Horizontal, tr("Name"));
    5.  
    6. TreeView->setModel(model);
    7. TreeView->show();
    To copy to clipboard, switch view to plain text mode 

    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
    Qt Code:
    1. query.lastInsertId().toString();
    To copy to clipboard, switch view to plain text mode 

  2. #2
    Join Date
    Oct 2009
    Posts
    151
    Thanks
    6
    Thanked 13 Times in 11 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Treeview - preselect node before displaying

    After much trial and error I've come up with a solution:

    With a known ID

    Qt Code:
    1. model->setQuery("SELECT * FROM people ORDER BY Name");
    2. int maxrows = model->rowCount(QModelIndex());
    3. int row = 0;
    4. while(row++ <= maxrows)
    5. if(ID == model->data(model->index(row, 0)).toInt())
    6. TreeView->selectionModel()->setCurrentIndex(model->index(row, 1),
    7. QItemSelectionModel::SelectCurrent);
    To copy to clipboard, switch view to plain text mode 

    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.

Similar Threads

  1. customize the root node of a treeview
    By billconan in forum Qt Programming
    Replies: 0
    Last Post: 10th November 2009, 08:06
  2. How to delete a node in treeview?
    By jasonjoy in forum Qt Programming
    Replies: 3
    Last Post: 10th November 2009, 06:07

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Qt is a trademark of The Qt Company.