Important: Please read the Qt Code of Conduct -

QSqlTableModel && setDatabase

  • Hi all,
    I'm using a QSqlTableModel in a project where I connect to a MySql DB this way:
    QSqlDatabase db;
    db = QSqlDatabase::addDatabase("QMYSQL");



    as you can see I don't specify the DB name. This is because my application use two database named "db1" and "db2".

    When I execute a query I do this:
    QSqlQuery query;
    query.exec("use db1");
    query.exec("select * from mytable; ");
    or this:
    QSqlQuery query;
    query.exec("select * from db1.mytable; ");

    but how can I use a QSqlTableModel?
    I tried with:
    without success...

  • Create a QSqlTableModel attach the model to your table tableView->setModel(model). Then You can use model->query("you sql command"), Or use QSqlQuery query... and model->setQuery(query).
    After the query I'm always doing model->query("Select * FROM table") and set the headerview again.

Log in to reply