QT+sqlite3+qtableview+qsqltablemodel联合使用最佳实践
1.qt创建工程
2.proj.pro
QT += core gui sql
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++17
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
FORMS += \
mainwindow.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
3.mainwindow.h
QT += core gui sql
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++17
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
FORMS += \
mainwindow.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
4.mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QSqlQuery>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
_db = QSqlDatabase::addDatabase("QSQLITE");
_db.setDatabaseName("demo.db");
// 数据库文件是否在应用程序目录下,因为在编码时,应用程序默认路径在.pro文件夹下,但是实际exe路径在的其debug或者release文件夹下
// 补充:不论linux还是windows,统一使用单斜杠作为分隔,在linux和windows下都能识别,能更好的跨平台
#if 0
// 发布时
QString path = qApp->applicationDirPath()+"/"+"demo.db";
#else
// 编译时
QString path = qApp->applicationDirPath()+"/../"+"demo.db";
#endif
if(QFile::exists(path))
{
// 存在则打开
_db.open();
}else{
// 不存在打开并创建数据库表 补充:SQLite是基于文件的数据库,当打开时如果数据库文件不存在将自动创建一个
_db.open();
QSqlQuery query;
// set为sqlite关键字,不能使用
bool bRet = query.exec("create table init(" \
"no INT PRIMARY KEY NOT NULL,"\
"name TEXT NOT NULL,"\
"content TEXT,"\
"description TEXT"\
");");
if(!bRet) {
_db.close();
QFile::remove(path);
}else{
// 此处演示了三种不同insert插入方法
query.exec("insert into init values" \
"(1, '启动界面背景', 'images/background.jpg', '请使用1920*1080的图片,图片格式可以为png、jpg。');");
query.exec("insert into init " \
"(no,name,content,description) values(2, '欢迎视频', '','进入启动界面后,循环播放的视频,必须为mp4格式,如果为空则循环播放欢迎音乐');");
query.exec("insert into init " \
"(no,name,description) values (3, '欢迎音乐','进去启动界面后,循环播放的音频文件,可选择mp3,wav格式');");
}
}
_pModel = new MyQSqlTableModel(this, _db);
_pModel->setTable("init");
// 三种提交方式,改动即提交,选择其他行时提交,手动提交;经实际测试,其中只有手动提交在显示效果上是最好的
//_pModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
_pModel->setHeaderData(0, Qt::Horizontal, tr("序号"));
_pModel->setHeaderData(1, Qt::Horizontal, tr("名称"));
_pModel->setHeaderData(2, Qt::Horizontal, tr("内容"));
_pModel->setHeaderData(3, Qt::Horizontal, tr("描述"));
//_pModel->sort(0, Qt::AscendingOrder); // 第0列升序排序
ui->tableView->setColumnHidden(0, true);
ui->tableView->setModel(_pModel);
// grid原本就是有多少格显示多少格,
ui->tableView->setShowGrid(false); // 可隐藏grid
// 只能单选
ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
// 以行作为选择标准
ui->tableView->setSelectionBehavior(QAbstractItemView::QAbstractItemView::SelectRows);
// 行头隐藏
ui->tableView->verticalHeader()->hide();
// 让列头可被点击,触发点击事件
ui->tableView->horizontalHeader()->setSectionsClickable(true);
// 去掉选中表格时,列头的文字高亮
ui->tableView->horizontalHeader()->setHighlightSections(false);
ui->tableView->horizontalHeader()->setBackgroundRole(QPalette::Background);
// 列头灰色
ui->tableView->horizontalHeader()->setStyleSheet("QHeaderView::section{background-color:rgb(225,225,225)};");
connect(ui->tableView->horizontalHeader(), SIGNAL(sectionClicked(int)), this, SLOT(sortByColumn(int)));
//_pModel->setFilter("no='2'");
_pModel->setSelectStatement("select name,content,description from init order by no desc");
_pModel->select();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::sortByColumn(int col)
{
QSqlTableModel *pMode = dynamic_cast<QSqlTableModel *>(ui->tableView->model());
bool ascending = (ui->tableView->horizontalHeader()->sortIndicatorSection()==col
&& ui->tableView->horizontalHeader()->sortIndicatorOrder()==Qt::DescendingOrder);
Qt::SortOrder order = ascending ? Qt::AscendingOrder : Qt::DescendingOrder;
pMode->sort(col, order);
}
4.mainwindow.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QTableView" name="tableView">
<property name="geometry">
<rect>
<x>15</x>
<y>111</y>
<width>771</width>
<height>441</height>
</rect>
</property>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>22</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
5.编译运行