Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Edit QSqlQueryModel (Or something similar) dynamically



  • I've currently got a small QSqlQueryModel that I'm using to display data from a database. I've looked at threads such as EditableQSqlQueryModels and such that allow the user to edit the data from in-app. However, is there anything out there for setting data dynamically before it shows in the model? I have a certain String in my database that I want to replace to display data before it is shown on the table.

    Thanks



  • Looks like calling QSqlQuery and then populating a QStandardItemModel is what best suits you



  • Just wondering what View I would use with this as well. I am using the QT creator just to lay it all out, unsure of what view/model to use though. I've tired QTreeView but get this -

    error: no matching function for call to 'QTreeView::setModel(QStandardItemModel&)'
    ui->roomList->setModel(model);

    Guessing I'm doing something wrong here?



  • Yes, you are passing the model by value rather than by pointer:

    ui->roomList->setModel(&model);



  • Thank you very much. Compiles well though and followed the exemplar for how to use QStandardItemModel. I've tried setting my QTreeView modal to it, however still a blank table.

    Code so far:

    QStandardItemModel model(4, 4);
    for(int row = 0; row < 4; row++) {
    for(int col = 0; col < 4; col++) {
    QStandardItem* item = new QStandardItem(QString("row %0, col %1").arg(row).arg(col));
    model.setItem(row, col, item);
    }
    }

    ui->roomList->setModel(&model);


  • since you are creating QStandardItemModel on the stack it probably ends up being deleted before the view is ever displayed



  • Apologies but I am lost as to what to do now then (Complete novice).

    Are you saying it's an issue because I already have the tree view created in Qt Creator and I'm trying to add into it in C++?


  • Lifetime Qt Champion

    @JPanda

    Hi
    Your QStandardItemModel must live long.
    So you better new it or else it will run out of scope.

    Example

    void Test() {
    QStandardItemModel model;
    } // scope ends here and Model variable is deleted.
    So you cannot give to some other object as its gone when Test() ends.

    so
    void Test() {
    QStandardItemModel * model = new QStandardItemModel (this); // thx VRonin. Remember to use a parent so u dont leak.
    }

    Now it will not be deleted when Test() ends.

    So while the ui->roomList have a long life, currently your model seems to die very shortly after being filled :)



  • @mrjj Fantastic it works fine thank. Thank you both very much.

    Learning the basics of C++ and coming from Java, the scoping is a little more difficult to get my head around. Thank you both though once again


Log in to reply