共计 1748 个字符,预计需要花费 5 分钟才能阅读完成。
基本理论
QSqlTableModel与QSqlRelationalTableModel,它们没有太大的不同,唯一的就是后者在前者的基础之上添加了外键(或者叫外码)的支持。
QSqlRelationalTableModel,该类为单张的数据库表提供了一个可编辑的数据模型,它支持外键。
参考代码:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QtSql/QSqlQuery>
#include<QtSql/QSqlDatabase>
#include<QtSql/QSqlRelationalTableModel>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
Ui::Widget *ui;
QSqlRelationalTableModel *model;
};
static bool createConnection()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("database.db");
if(!db.open()) return false;
QSqlQuery query;
query.exec("create table student (id int primary key, name vchar,course int)");
query.exec("insert into student values (1,'yafei0',1)");
query.exec("insert into student values (2,'yafei1',1)");
query.exec("insert into student values (3,'yafei2',2)");
query.exec("create table course (id int primary key, name vchar, teacher vchar)");
query.exec("insert into course values (1,'Math','yafeilinux1')");
query.exec("insert into course values (2,'English','yafeilinux2')");
query.exec("insert into course values (3,'Computer','yafeilinux3')");
return true;
}
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
model = new QSqlRelationalTableModel(this);
model->setEditStrategy(QSqlTableModel::OnFieldChange); //属性变化时写入数据库
model->setTable("student");
model->setRelation(2,QSqlRelation("course","id","name"));
//将student表的第三个属性设为course表的id属性的外键,并将其显示为course表的name属性的值
model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("Name"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("Course"));
model->select();
ui->tableView->setModel(model);
}
Widget::~Widget()
{
delete ui;
}
实验结果
正文完
请博主喝杯咖啡吧!