缓存表示例界面:
展示了如何使用表视图来访问数据库,缓存对数据的任何更改,直到用户使用按钮明确提交这些更改
该示例由一个类TableEditor组成,TableEditor是一个自定义对话框小部件,允许用户修改存储在数据库中的数据
TableEditor类定义
- TableEditor类继承了QWidget,作为主窗口
class TableEditor : public QWidget
{
Q_OBJECT
public:
explicit TableEditor(const QString &tableName, QWidget *parent = nullptr);
private slots:
void submit();
private:
QPushButton *submitButton;
QPushButton *revertButton;
QPushButton *quitButton;
QDialogButtonBox *buttonBox;
QSqlTableModel *model;
};
TableEditor构造函数接受两个参数:第一个是对TableEditor对象将操作的数据库表的引用。另一个是指向父小部件的指针,并被传递给基类构造函数
QSqlTableModel类可用于向视图类(如QTableView)提供数据。QSqlTableModel类提供了一个可编辑的数据模型,使得从单个表中读写数据库记录成为可能。它建立在较低级别的SqlQuery类之上,该类提供了执行和操作SQL语句的方法。
另外还展示如何使用表视图来缓存对数据的任何更改,直到明确请求提交它们。为此,我们需要在模型和编辑器按钮之外声明一个submit()槽函数
- main函数主要代码
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
if (!createConnection())
return 1;
TableEditor editor("person");
editor.show();
return app.exec();
}
- createConnection()函数定义在connection.h的头文件中,此函数创建内存临时数据库,建立三个数据表,并添加一些记录
static bool createConnection()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
if (!db.open()) {
QMessageBox::critical(nullptr, QObject::tr("Cannot open database"),
QObject::tr("Unable to establish a database connection.\n"
"This example needs SQLite support. Please read "
"the Qt SQL driver documentation for information how "
"to build it.\n\n"
"Click Cancel to exit."), QMessageBox::Cancel);
return false;
}
QSqlQuery query;
query.exec("create table person (id int primary key, "
"firstname varchar(20), lastname varchar(20))");
query.exec("insert into person values(101, 'Danny', 'Young')");
query.exec("insert into person values(102, 'Christine', 'Holand')");
query.exec("insert into person values(103, 'Lars', 'Gordon')");
query.exec("insert into person values(104, 'Roberto', 'Robitaille')");
query.exec("insert into person values(105, 'Maria', 'Papadopoulos')");
query.exec("create table items (id int primary key,"
"imagefile int,"
"itemtype varchar(20),"
"description varchar(100))");
query.exec("insert into items "
"values(0, 0, 'Qt',"
"'Qt is a full development framework with tools designed to "
"streamline the creation of stunning applications and "
"amazing user interfaces for desktop, embedded and mobile "
"platforms.')");
query.exec("insert into items "
"values(1, 1, 'Qt Quick',"
"'Qt Quick is a collection of techniques designed to help "
"developers create intuitive, modern-looking, and fluid "
"user interfaces using a CSS & JavaScript like language.')");
query.exec("insert into items "
"values(2, 2, 'Qt Creator',"
"'Qt Creator is a powerful cross-platform integrated "
"development environment (IDE), including UI design tools "
"and on-device debuggi