C/C++?Qt?數(shù)據(jù)庫(kù)與TableView實(shí)現(xiàn)多組件聯(lián)動(dòng)
Qt 數(shù)據(jù)庫(kù)組件與TableView組件實(shí)現(xiàn)聯(lián)動(dòng),以下案例中實(shí)現(xiàn)了,當(dāng)用戶點(diǎn)擊并選中TableView組件內(nèi)的某一行時(shí),我們通過該行中的name字段查詢并將查詢結(jié)果關(guān)聯(lián)到ListView組件內(nèi),同時(shí)將TableView中選中行的字段分別顯示在窗體底部的LineEdit編輯內(nèi),該案例具體實(shí)現(xiàn)細(xì)節(jié)如下。
首先在UI界面中繪制好需要的控件,左側(cè)放一個(gè)TableView組件,右側(cè)是一個(gè)ListView組件,底部放三個(gè)LineEdit組件,界面如下:

我們還是需要?jiǎng)?chuàng)建兩張表結(jié)構(gòu),表Student用于存儲(chǔ)學(xué)生的基本信息,表StudentTimetable存儲(chǔ)的是每個(gè)學(xué)生所需要學(xué)習(xí)的課程列表,執(zhí)行后創(chuàng)建數(shù)據(jù)表。
void InitMultipleSQL()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("./lyshark.db");
if (!db.open())
{
std::cout << db.lastError().text().toStdString()<< std::endl;
return;
}
// 執(zhí)行SQL創(chuàng)建表
db.exec("DROP TABLE Student");
db.exec("CREATE TABLE Student ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"name VARCHAR(40) NOT NULL, "
"age INTEGER NOT NULL)"
);
// 批量創(chuàng)建數(shù)據(jù)
// https://www.cnblogs.com/lyshark
QStringList name_list; name_list << "lyshark" << "lisi" << "wangwu";
QStringList age_list; age_list << "25" << "34" << "45";
// 綁定并插入數(shù)據(jù)
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();
}
}
// ------------------------------------------------
// 創(chuàng)建第二張表,與第一張表通過姓名關(guān)聯(lián)起來(lái)
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();
}
程序運(yùn)行后,構(gòu)造函數(shù)MainWindow::MainWindow(QWidget *parent)內(nèi)初始化表格,查詢Student表內(nèi)記錄,將查詢到的指針綁定到theSelection模型上,綁定后再將綁定指針加入到dataMapper組件映射中,即可實(shí)現(xiàn)初始化,其初始化代碼如下:
#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; // 數(shù)據(jù)模型
QItemSelectionModel *theSelection; // 選擇模型
QDataWidgetMapper *dataMapper; // 數(shù)據(jù)界面映射
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;
}
// 查詢數(shù)據(jù)表中記錄
qryModel=new QSqlQueryModel(this);
qryModel->setQuery("SELECT * FROM Student ORDER BY id");
if (qryModel->lastError().isValid())
{
return;
}
// 設(shè)置TableView表頭數(shù)據(jù)
qryModel->setHeaderData(0,Qt::Horizontal,"ID");
qryModel->setHeaderData(1,Qt::Horizontal,"Name");
qryModel->setHeaderData(2,Qt::Horizontal,"Age");
// 將數(shù)據(jù)綁定到模型上
theSelection=new QItemSelectionModel(qryModel);
ui->tableView->setModel(qryModel);
ui->tableView->setSelectionModel(theSelection);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
// 創(chuàng)建數(shù)據(jù)映射
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();
// 綁定信號(hào),當(dāng)鼠標(biāo)選擇時(shí),在底部編輯框中輸出
// https://www.cnblogs.com/lyshark
connect(theSelection,SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),this,SLOT(on_currentRowChanged(QModelIndex,QModelIndex)));
}
MainWindow::~MainWindow()
{
delete ui;
}
此時(shí)這個(gè)程序運(yùn)行后會(huì)得到表內(nèi)數(shù)據(jù):

接著我們需要綁定TableView表格的on_currentRowChanged()事件,當(dāng)用戶點(diǎn)擊TableView表格中的某個(gè)屬性是則自動(dòng)觸發(fā)該函數(shù),在此函數(shù)內(nèi)我們完成對(duì)其他組件的填充.
1.通過currentIndex方法獲取到當(dāng)前表所在行
2.通過當(dāng)前行號(hào)查詢表中姓名,并帶入StudentTimetable表查該表中記錄
3.循環(huán)獲取該用戶的數(shù)據(jù),并將timetable字段提取出來(lái)放入QStringList容器
4.將數(shù)據(jù)直接關(guān)聯(lián)到ListView數(shù)據(jù)表中
// 鼠標(biāo)點(diǎn)擊后的處理槽函數(shù)
void MainWindow::on_currentRowChanged(const QModelIndex &current, const QModelIndex &previous)
{
Q_UNUSED(previous);
if (!current.isValid())
{
return;
}
dataMapper->setCurrentModelIndex(current);
// 獲取到記錄開頭結(jié)尾
bool first=(current.row()==0); // 是否首記錄
bool last=(current.row()==qryModel->rowCount()-1);// 是否尾記錄
std::cout << "IsFirst: " << first << "IsLast: " << last << std::endl;
// 獲取name字段數(shù)據(jù)
int curRecNo=theSelection->currentIndex().row(); // 獲取當(dāng)前行號(hào)
QSqlRecord curRec=qryModel->record(curRecNo); // 獲取當(dāng)前記錄
QString uname = curRec.value("name").toString();
std::cout << "Student Name = " << uname.toStdString() << std::endl;
// 查StudentTimetable表中所有數(shù)據(jù)
// 根據(jù)姓名過濾出該用戶的所有數(shù)據(jù)
QSqlQuery query;
query.prepare("select * from StudentTimetable where name = :x");
query.bindValue(":x",uname);
query.exec();
// 循環(huán)獲取該用戶的數(shù)據(jù),并將timetable字段提取出來(lái)放入QStringList容器
// https://www.cnblogs.com/lyshark
QSqlRecord rec = query.record();
QStringList the_data;
while(query.next())
{
int index = rec.indexOf("timetable");
QString data = query.value(index).toString();
std::cout << "User timetable = " << data.toStdString() << std::endl;
the_data.append(data);
}
// 關(guān)聯(lián)到ListView數(shù)據(jù)表中
QStringListModel *model;
model = new QStringListModel(the_data);
ui->listView->setModel(model);
ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
}
當(dāng)綁定選中事件時(shí),程序運(yùn)行效果如下:

針對(duì)底部按鈕處理事件相對(duì)來(lái)說較為簡(jiǎn)單,其實(shí)現(xiàn)原理就是調(diào)用了TableView默認(rèn)提供的一些函數(shù)而已,代碼如下:
// 刷新tableView的當(dāng)前選擇行
// https://www.cnblogs.com/lyshark
void MainWindow::refreshTableView()
{
int index=dataMapper->currentIndex();
QModelIndex curIndex=qryModel->index(index,0); // 定位到低0行0列
theSelection->clearSelection(); // 清空選擇項(xiàng)
theSelection->setCurrentIndex(curIndex,QItemSelectionModel::Select);//設(shè)置剛插入的行為當(dāng)前選擇行
}
// 第一條記錄
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();
}
最終運(yùn)行效果如下所示:

文章出處:https://www.cnblogs.com/lyshark
到此這篇關(guān)于C/C++?Qt?數(shù)據(jù)庫(kù)與TableView多組件聯(lián)動(dòng)的文章就介紹到這了,更多相關(guān)C++?QT多組件聯(lián)動(dòng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Qt GUI圖形圖像開發(fā)之QT表格控件QTableView,QTableWidget復(fù)雜表頭(多行表頭) 及凍結(jié)、固定特定的行的詳細(xì)方法與實(shí)例
- Qt GUI圖形圖像開發(fā)之Qt表格控件QTableView簡(jiǎn)單使用方法及QTableView與QTableWidget區(qū)別
- Qt GUI圖形圖像開發(fā)之QT表格控件QTableView詳細(xì)使用方法與實(shí)例
- Qt實(shí)現(xiàn)導(dǎo)出QTableWidget/QTableView數(shù)據(jù)
- C++中的Qt?QTableView詳解
- Qt中TableView與TreeView組件聯(lián)動(dòng)實(shí)現(xiàn)
相關(guān)文章
C 語(yǔ)言基礎(chǔ)教程(我的C之旅開始了)[十]
C 語(yǔ)言基礎(chǔ)教程(我的C之旅開始了)[十]...2007-02-02
C語(yǔ)言如何計(jì)算兩個(gè)數(shù)的最小公倍數(shù)
這篇文章主要介紹了C語(yǔ)言如何計(jì)算兩個(gè)數(shù)的最小公倍數(shù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
Qt結(jié)合OpenCV部署yolov5的實(shí)現(xiàn)
本文主要介紹了Qt結(jié)合OpenCV部署yolov5的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
VC++?2019?"const?char*"類型的實(shí)參與"LPCTSTR"
這篇文章主要給大家介紹了關(guān)于VC++?2019?"const?char*"類型的實(shí)參與"LPCTSTR"類型的形參不兼容的解決方法,文中通過圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2023-03-03
C++類和對(duì)象之類的6個(gè)默認(rèn)成員函數(shù)詳解
類是對(duì)某一事物的抽象描述,具體地講類是C++中的一種構(gòu)造的數(shù)據(jù)類型,下面這篇文章主要給大家介紹了關(guān)于C++類和對(duì)象之類的6個(gè)默認(rèn)成員函數(shù)的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02
c++使用Easyx圖形庫(kù)實(shí)現(xiàn)飛機(jī)大戰(zhàn)
本文詳細(xì)講解了c++使用Easyx圖形庫(kù)實(shí)現(xiàn)飛機(jī)大戰(zhàn),文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-12-12

