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.