QSqlQueryModel類為SQL的結(jié)果集提供了一個(gè)只讀的數(shù)據(jù)模型,下面我們先利用這個(gè)類進(jìn)行一個(gè)最簡(jiǎn)單的操作.
常用函數(shù)
void QSqlQueryModel::setQuery ("SQL語句") // 執(zhí)行SQL語句,此處還可以傳入QSqlQuery對(duì)象,此時(shí)可以利用QSqlQuery類的某些特性,如預(yù)操作等.
setHeaderData() //設(shè)置水平頭標(biāo)題
columnCount(); //獲得列數(shù)
columnCount(); //獲得列數(shù)
QSqlRecord QSqlQueryModel::record ( int row ) const //返回row行包含的信息,可訪問單條的記錄
QModelIndex QAbstractItemModel::index ( int row, int column, const QModelIndex & parent = QModelIndex() ) //返回指定的行和列的索引(index)
index.data() //返回index索引的值
query() //返回與QSqlQuery相關(guān)的模型
- QSqlQueryModel *model = new QSqlQueryModel;
- model->setQuery(“select * from student”);
- model->setHeaderData(0, Qt::Horizontal, tr(“id”));
- model->setHeaderData(1, Qt::Horizontal, tr(“name”));
- QTableView *view = new QTableView;
- view->setModel(model);
- view->show();
利用query執(zhí)行SQL語句
- QSqlQuery query = model->query();
- query.exec("select name from student where id = 1");
- query.next();
- qDebug() << query.value(0).toString();
因?yàn)镼SqlQueryMode模型默認(rèn)是只讀的,所以我們?cè)诖翱谏喜⒉荒軐?duì)表格中的內(nèi)容進(jìn)行修改。但是我們可以創(chuàng)建自己的模型,然后按照我們自己的需要來顯示數(shù)據(jù)和修改數(shù)據(jù)。如果要想使其可讀寫,需要自己的類繼承自QSqlQueryModel,并且重寫setData() 和 flags() 兩個(gè)函數(shù),如果我們要改變數(shù)據(jù)的顯示,就要重寫data() 函數(shù)。
- Qt::ItemFlags MySqlQueryModel::flags(const QModelIndex &index) const
- {
- Qt::ItemFlags flags = QSqlQueryModel::flags(index);
- if (index.column() == 1)
- flags |= Qt::ItemIsEditable;
- return flags;
- }
-
- bool MySqlQueryModel::setData(const QModelIndex &index, const QVariant &value, int )
- {
- QModelIndex primaryKeyIndex = QSqlQueryModel::index(index.row(), 0);
- int id = data(primaryKeyIndex).toInt();
-
- clear();
- bool isOk;
- if (index.column() == 1)
- {
- QSqlQuery query;
- query.prepare("UPDATE STUDENT SET NAME = :name WHERE id = :id");
- query.bindValue(":name","小五");
- query.bindValue(":id",id);
- isOk = query.exec();
-
- refresh();
- return isOK;
- }
- return false;
- }
-
- void MySqlQueryModel::refresh()
- {
- setQuery("select * from student");
- setHeaderData(0, Qt::Horizontal, QObject::tr("學(xué)號(hào)ID"));
- setHeaderData(1, Qt::Horizontal, QObject::tr("名字"));
- }
-
-
- QVariant MySqlQueryModel::data(const QModelIndex &index, int role) const
-
- {
- QVariant value = QSqlQueryModel::data(index, role);
- if (role == Qt::TextColorRole && index.column() == 0)
- return qVariantFromValue(QColor(Qt::red));
- return value;
- }
posted on 2011-11-22 15:16
再生的雄鷹 閱讀(2937)
評(píng)論(0) 編輯 收藏 引用