Important: Please read the Qt Code of Conduct -

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();
        QSqlQuery* qry = new QSqlQuery(conn.mydb);
        qry->prepare("select user from usertable  where NAME='" +ui->textEdit->toPlainText()+ "'");

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

  • Lifetime Qt Champion

    @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:

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

    With query.value(0) you get value of first column, with query.value(1) the value from second and so on. Use 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!


  • Lifetime Qt Champion


    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);

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

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

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

Log in to reply