Qt 資料庫組件與TableView組件實作聯動,以下案例中實作了,當用戶點擊并選中TableView組件內的某一行時,我們通過該行中的name欄位查詢并將查詢結果關聯到ListView組件內,同時將TableView中選中行的欄位分別顯示在表單底部的LineEdit編輯內,該案例具體實作細節如下,
首先在UI界面中繪制好需要的控制元件,左側放一個TableView組件,右側是一個ListView組件,底部放三個LineEdit組件,界面如下:

我們還是需要創建兩張表結構,表Student用于存盤學生的基本資訊,表StudentTimetable存盤的是每個學生所需要學習的課程串列,執行后創建資料表,
void InitMultipleSQL()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("./lyshark.db");
if (!db.open())
{
std::cout << db.lastError().text().toStdString()<< std::endl;
return;
}
// 執行SQL創建表
db.exec("DROP TABLE Student");
db.exec("CREATE TABLE Student ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"name VARCHAR(40) NOT NULL, "
"age INTEGER NOT NULL)"
);
// 批量創建資料
// https://www.cnblogs.com/lyshark
QStringList name_list; name_list << "lyshark" << "lisi" << "wangwu";
QStringList age_list; age_list << "25" << "34" << "45";
// 系結并插入資料
QSqlQuery query;
query.prepare("INSERT INTO Student(name,age) ""VALUES (:name, :age)");
if(name_list.size() == age_list.size())
{
for(int x=0;x< name_list.size();x++)
{
query.bindValue(":name",name_list[x]);
query.bindValue(":age",age_list[x]);
query.exec();
}
}
// ------------------------------------------------
// 創建第二張表,與第一張表通過姓名關聯起來
db.exec("DROP TABLE StudentTimetable");
db.exec("CREATE TABLE StudentTimetable("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"name VARCHAR(40) NOT NULL, "
"timetable VARCHAR(128) NOT NULL"
")");
db.exec("INSERT INTO StudentTimetable(name,timetable) VALUES ('lyshark','AAA')");
db.exec("INSERT INTO StudentTimetable(name,timetable) VALUES ('lyshark','BBB')");
db.exec("INSERT INTO StudentTimetable(name,timetable) VALUES ('lyshark','CCC')");
db.exec("INSERT INTO StudentTimetable(name,timetable) VALUES ('lisi','QQQ')");
db.exec("INSERT INTO StudentTimetable(name,timetable) VALUES ('lisi','WWW')");
db.exec("INSERT INTO StudentTimetable(name,timetable) VALUES ('wangwu','EEE')");
db.commit();
db.close();
}
程式運行后,建構式MainWindow::MainWindow(QWidget *parent)內初始化表格,查詢Student表內記錄,將查詢到的指標系結到theSelection模型上,系結后再將系結指標加入到dataMapper組件映射中,即可實作初始化,其初始化代碼如下:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>
#include <iostream>
#include <QStringList>
#include <QString>
#include <QVariant>
#include <QDataWidgetMapper>
#include <QtSql>
#include <QStandardItem>
#include <QStringList>
#include <QStringListModel>
QSqlQueryModel *qryModel; // 資料模型
QItemSelectionModel *theSelection; // 選擇模型
QDataWidgetMapper *dataMapper; // 資料界面映射
MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{
ui->setupUi(this);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("./lyshark.db");
if (!db.open())
{
std::cout << db.lastError().text().toStdString()<< std::endl;
return;
}
// 查詢資料表中記錄
qryModel=new QSqlQueryModel(this);
qryModel->setQuery("SELECT * FROM Student ORDER BY id");
if (qryModel->lastError().isValid())
{
return;
}
// 設定TableView表頭資料
qryModel->setHeaderData(0,Qt::Horizontal,"ID");
qryModel->setHeaderData(1,Qt::Horizontal,"Name");
qryModel->setHeaderData(2,Qt::Horizontal,"Age");
// 將資料系結到模型上
theSelection=new QItemSelectionModel(qryModel);
ui->tableView->setModel(qryModel);
ui->tableView->setSelectionModel(theSelection);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
// 創建資料映射
dataMapper= new QDataWidgetMapper();
dataMapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
dataMapper->setModel(qryModel);
dataMapper->addMapping(ui->lineEdit_id,0);
dataMapper->addMapping(ui->lineEdit_name,1);
dataMapper->addMapping(ui->lineEdit_age,2);
dataMapper->toFirst();
// 系結信號,當滑鼠選擇時,在底部編輯框中輸出
// https://www.cnblogs.com/lyshark
connect(theSelection,SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),this,SLOT(on_currentRowChanged(QModelIndex,QModelIndex)));
}
MainWindow::~MainWindow()
{
delete ui;
}
此時這個程式運行后會得到表內資料:

接著我們需要系結TableView表格的on_currentRowChanged()事件,當用戶點擊TableView表格中的某個屬性是則自動觸發該函式,在此函式內我們完成對其他組件的填充.
- 1.通過
currentIndex方法獲取到當前表所在行 - 2.通過當前行號查詢表中姓名,并帶入
StudentTimetable表查該表中記錄 - 3.回圈獲取該用戶的資料,并將
timetable欄位提取出來放入QStringList容器 - 4.將資料直接關聯到
ListView資料表中
// 滑鼠點擊后的處理槽函式
void MainWindow::on_currentRowChanged(const QModelIndex ¤t, const QModelIndex &previous)
{
Q_UNUSED(previous);
if (!current.isValid())
{
return;
}
dataMapper->setCurrentModelIndex(current);
// 獲取到記錄開頭結尾
bool first=(current.row()==0); // 是否首記錄
bool last=(current.row()==qryModel->rowCount()-1);// 是否尾記錄
std::cout << "IsFirst: " << first << "IsLast: " << last << std::endl;
// 獲取name欄位資料
int curRecNo=theSelection->currentIndex().row(); // 獲取當前行號
QSqlRecord curRec=qryModel->record(curRecNo); // 獲取當前記錄
QString uname = curRec.value("name").toString();
std::cout << "Student Name = " << uname.toStdString() << std::endl;
// 查StudentTimetable表中所有資料
// 根據姓名過濾出該用戶的所有資料
QSqlQuery query;
query.prepare("select * from StudentTimetable where name = :x");
query.bindValue(":x",uname);
query.exec();
// 回圈獲取該用戶的資料,并將timetable欄位提取出來放入QStringList容器
// https://www.cnblogs.com/lyshark
QSqlRecord rec = query.record();
QStringList the_data;
while(query.next())
{
int index = rec.indexOf("timetable");
QString data = https://www.cnblogs.com/LyShark/p/query.value(index).toString();
std::cout <<"User timetable = " << data.toStdString() << std::endl;
the_data.append(data);
}
// 關聯到ListView資料表中
QStringListModel *model;
model = new QStringListModel(the_data);
ui->listView->setModel(model);
ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
}
當系結選中事件時,程式運行效果如下:

針對底部按鈕處理事件相對來說較為簡單,其實作原理就是呼叫了TableView默認提供的一些函式而已,代碼如下:
// 重繪tableView的當前選擇行
// https://www.cnblogs.com/lyshark
void MainWindow::refreshTableView()
{
int index=dataMapper->currentIndex();
QModelIndex curIndex=qryModel->index(index,0); // 定位到低0行0列
theSelection->clearSelection(); // 清空選擇項
theSelection->setCurrentIndex(curIndex,QItemSelectionModel::Select);//設定剛插入的行為當前選擇行
}
// 第一條記錄
void MainWindow::on_pushButton_clicked()
{
dataMapper->toFirst();
refreshTableView();
}
// 最后一條記錄
void MainWindow::on_pushButton_2_clicked()
{
dataMapper->toLast();
refreshTableView();
}
// 前一條記錄
void MainWindow::on_pushButton_3_clicked()
{
dataMapper->toPrevious();
refreshTableView();
}
// 下一條記錄
void MainWindow::on_pushButton_4_clicked()
{
dataMapper->toNext();
refreshTableView();
}
最終運行效果如下所示:

著作權宣告: 本博客文章與代碼均為學習時整理的筆記,博客中除去明確標注有參考文獻的文章,其他文章 [均為原創] 作品,轉載請 [添加出處] ,您添加出處是我創作的動力!
本博客所有文章除參考文獻特別宣告外,均采用 知識共享 署名-非商業性使用 [CC BY-NC-ND 4.0] 國際許可協議
警告:如果您惡意轉載本人文章并被本人發現,則您的整站文章,將會變為我的原創作品,請相互尊重 !
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/376822.html
標籤:C++
下一篇:我好像發現了一個Go的Bug?
