Retrieving database data to qtablewidget



  • I am new to qt programming! I found a video tutorial in which data is being retireved to a qtableview! But since I am new model view programming seems to be bit complex! The following method is ueds to retrieve data to a qtableview(It works)!

    void MainWindow::on_pushButton_4_clicked()
    {
    MainWindow conn;

        QSqlQueryModel * modal = new QSqlQueryModel();
        conn.connOpen();
        QSqlQuery* qry = new QSqlQuery(conn.mydb);
        qry->prepare("select user from usertable  where NAME='" +ui->textEdit->toPlainText()+ "'");
        qry->exec();
        modal->setQuery(*qry);
        ui->tableView_2->setModel(modal);
    
        conn.connClose();
    

    }
    conn is used to provide the database connection! How can I change the above method to retreive data to a qtablewidget?


  • Moderators

    @Lasith Using QTableWidget would be even more complex as you would need to fill the table manually parsing the query result. But if you really want then see here: http://doc.qt.io/qt-5/qsqlquery.html

    QSqlQuery query("SELECT country FROM artist");
    while (query.next()) {
        QString country = query.value(0).toString();
        doSomething(country);
     }
    

    With query.value(0) you get value of first column, with query.value(1) the value from second and so on. Use http://doc.qt.io/qt-5/qtablewidget.html#setItem to set each cell.



  • @jsulm Thanx mate



  • As in QTableWidget the setModel method is private you cannot use the model directly for setting data into a QTableWidget.

    One possible solution would be that you add every single cell of the table as a QTableWidgetItem by hand.
    In my opinion this solution would be more complex than working with models.

    BTW: the code you posted as a sample is not really worth to mention.
    e.g. every time you press your pushbutton4 a new model will be allocated and never released!

    regards
    Karl-Heinz


  • Lifetime Qt Champion

    Hi,

    To add to @karlheinzreichel, there's no need to allocate QSqlQuery on the heap like you do. Just put it on the stack.



  • You can use QSqlTableModel instead to do this.
    //create a database object
    QSqlDatabase db = QSqlDatabase::addDatabase(driver, name);
    db.setDatabaseName(database_path);
    db.open();

    //bound the database to the QSqlTableModel
    QSqlTableModel *model = new QSqlTableModel(this, db);
    model.setTable(table_name);
    model.select();

    //Now you can retrieve data from the database via the model
    QModelIndex idx = model.index(row, column);
    model.data(idx);

    For details, you can search the official reference online or in QtCreator:
    Ctrl + K,
    then type: ? QSqlTableModel.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.