[QT] -- display the content in the SQLite database table in tableview

Source: Internet
Author: User

QT and sqlite3 have been used in recent work. Here we record some of the knowledge points used: specifically, tableview is used in the QT widget to display the content in the SQLite database table.

Suppose there are database files test. DB, tables (ID integer, name nvarchar (20), age integer), and there are several pieces of data ...... (Randomly created tables)

Use qtcreator to create a window based on the widget class, drag a tableview to the widget, save the window, and perform the following operations:

1. Add the header file qtsql/qsql. H, qtsql/qsqldatabase, qtsql/qsqlquery, and qtsql/qsqlquerymodel to the widget. h file.

2. Add QT + = SQL IN THE. Pro project file

3. Add the following code to the widget constructor in widget. cpp:

Qsqdatabase DB = qsqldatabase: adddatabase ("SQLite ");

DB. setdatabasename ("test. DB ");

If (! DB. open ())

{

// Handle errors

}

Static qsqlquerymodel * model = new qsqlquerymodel (ui-> tableview );

Model-> setquery (qstring ("select * from table ;"));

Model-> setheaderdata (0, QT: horizontal, qobject: TR ("no "));

Model-> setheaderdata (1, QT: horizontal, qobject: TR ("name "));

Model-> setheaderdata (2, QT: horizontal, qobject: TR ("Age "));

UI-> tableview-> setmodel (model );

DB-> close ();

In this way, the content in the table is displayed in tableview.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.