Important: Please read the Qt Code of Conduct -

Populate QTreeView from database tables

  • Hi,

    I am relatively new to Qt (I use PyQt). I would appreciate your help regarding the following design problem.

    I have to develop a treeview which would have 4 levels (For example, Country->County/Province->City->Town). The data for each level is stored in a seperate table in a SQL database. The treeview should be editable. It should have drag and drop, reorder functionalities. By reorder functionality I mean that the users would be able to reorder the branches of a node by dragging and dropping. (In our example, towns of a city would appear in a particular order that the user wants.)

    I was thinking of implementing QAbstractProxyModel with four different QSqlQueryModel, but then when reordering is allowed
    mapping between the indices looks a bit complicated.

    What is the best way to implement this? I was thinking of having a column in the respective database tables to
    store the order of the branches, but then different users might want different orders. It is therefore
    good to store the sort order in a session file. As a result I am thinking of implementing
    QAbstractItemModel and store the tree structure locally, but then keeping the database
    and the local copy of the tree in synchronisation becomes a bit difficult...

    I would appreciate your suggestions and comments .

    Thank you in advance,

  • This one example of mine, this is made using postgresql
    @ QPushButton *button;
    _model = new QSqlQueryModel(this);
    QSignalMapper *signalMapperEdit = new QSignalMapper(this);
    QSignalMapper *signalMapperRemove = new QSignalMapper(this);
    _model->setQuery("SELECT id_person, email, first_name, last_name, job_position FROM person ORDER BY id_person");
    QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);
    _model->setHeaderData(0, Qt::Horizontal,"ID");
    _model->setHeaderData(1, Qt::Horizontal,"Email");
    _model->setHeaderData(2, Qt::Horizontal,"First Name");
    _model->setHeaderData(3, Qt::Horizontal,"Last Name");
    _model->setHeaderData(4, Qt::Horizontal,"Job Position");
    _model->setHeaderData(5, Qt::Horizontal,"");
    _model->setHeaderData(6, Qt::Horizontal,"");

  • I also would like to have some guideline in how to populate QTreeView from a database. Any help is appreciated.

Log in to reply