QT数据库编程
ui界面
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QButtonGroup>
#include <QFileDialog>
#include <QMessageBox>
MainWindow::MainWindow(QWidget* parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);// this->setCentralWidget(ui->splitter);ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection); //设置择的模式只可以选中一个ui->tableView->setAlternatingRowColors(true); //设置不同行颜色//设置分组QButtonGroup* group = new QButtonGroup(this);group->addButton(ui->radioButton);group->addButton(ui->radioButton_2);
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_pushButton_clicked()
{QString file = QFileDialog::getOpenFileName(this, "选择文件", "../", "SQLITE(*.*)");if (file.isEmpty())return;db = QSqlDatabase::addDatabase("QSQLITE"); //添加驱动db.setDatabaseName(file); //加入文件if (!db.open())QMessageBox::warning(this, "错误", "打开失败");else {openTable(); //打开数据库表格}qDebug() << "完成";
}void MainWindow::do_current_changed(const QModelIndex& current, const QModelIndex&)
{Q_UNUSED(current);qDebug() << "当前改变";ui->pushButton_8->setEnabled(tabModel->isDirty()); //是改过的
}void MainWindow::do_current_row_changed(const QModelIndex& current, const QModelIndex&)
{qDebug() << "点击了单元格";if (!current.isValid()) {ui->label_10->clear();return;}ui->pushButton_8->setEnabled(true);//映射dataMapper->setCurrentIndex(current.row());QSqlRecord curRecord = tabModel->record(current.row());if (!curRecord.isEmpty()) {qDebug() << "数据" << curRecord;}
}void MainWindow::openTable()
{//创建模型,打开数据库表格tabModel = new QSqlTableModel(this, db);tabModel->setTable("test"); //设置数据库表名称tabModel->setEditStrategy(QSqlTableModel::OnManualSubmit); //手动提交tabModel->setSort(tabModel->fieldIndex("id"), Qt::DescendingOrder); //按id 降序排序, 升序 AscendingOrderif (!tabModel->select()) {QMessageBox::critical(this, "错误", tabModel->lastError().text());}ui->statusbar->showMessage(QString("记录条数为 %1").arg(tabModel->rowCount()));//设置字段显示的标题tabModel->setHeaderData(tabModel->fieldIndex("id"), Qt::Horizontal, "ID号");tabModel->setHeaderData(tabModel->fieldIndex("name"), Qt::Horizontal, "姓名");// model /viewselModel = new QItemSelectionModel(tabModel, this);ui->tableView->setModel(tabModel);ui->tableView->setSelectionModel(selModel); //注意:必须先设置模型在设置选择模型,否则不生效// ui->tableView->setColumnHidden(tabModel->fieldIndex("id"), true); //隐藏数据//代理QStringList str;str << "男"<< "女";delegateSex.setItems(str, false);ui->tableView->setItemDelegateForColumn(tabModel->fieldIndex("name"), &delegateSex);//字段与widget映射dataMapper = new QDataWidgetMapper(this);dataMapper->setModel(tabModel);dataMapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit); //数据自动提交dataMapper->addMapping(ui->spinBox, tabModel->fieldIndex("id"));dataMapper->addMapping(ui->lineEdit, tabModel->fieldIndex("name"));dataMapper->toFirst(); //显示第一条记录// 状态发生变化// ui->pushButton->setEnabled(false);//获取字段名更新QSqlRecord emptyRec = tabModel->record();qDebug() << "emptyRec = " << emptyRec;for (int i = 0; i < emptyRec.count(); ++i) {ui->comboBox->addItem(emptyRec.fieldName(i));}//信号连接connect(selModel, &QItemSelectionModel::currentChanged, this, &MainWindow::do_current_changed);connect(selModel, &QItemSelectionModel::currentRowChanged, this, &MainWindow::do_current_row_changed);
}void MainWindow::on_pushButton_3_clicked()
{QModelIndex index = ui->tableView->currentIndex();QSqlRecord rec = tabModel->record();rec.setValue(tabModel->fieldIndex("name"), "王五");tabModel->insertRecord(index.row(), rec);selModel->clearSelection();selModel->setCurrentIndex(tabModel->index(tabModel->rowCount() - 1, 1), QItemSelectionModel::Select);//更新状态栏ui->statusbar->showMessage(QString("记录条数为 %1").arg(tabModel->rowCount()));
}void MainWindow::on_pushButton_2_clicked()
{QSqlRecord rec = tabModel->record();rec.setValue(tabModel->fieldIndex("name"), "王五");tabModel->insertRecord(tabModel->rowCount(), rec);selModel->clearSelection();selModel->setCurrentIndex(tabModel->index(tabModel->rowCount() - 1, 1), QItemSelectionModel::Select);//更新状态栏ui->statusbar->showMessage(QString("记录条数为 %1").arg(tabModel->rowCount()));
}void MainWindow::on_pushButton_4_clicked()
{QModelIndex index = ui->tableView->currentIndex();tabModel->removeRow(index.row());ui->statusbar->showMessage(QString("记录条数为 %1").arg(tabModel->rowCount()));
}void MainWindow::on_pushButton_5_clicked()
{QString aFile = QFileDialog::getOpenFileName(this, "选择图片", "", "(*.jpg)");if (aFile.isEmpty())return;QFile* file = new QFile(aFile, this);if (file->open(QIODevice::ReadOnly)) {QByteArray arr = file->readAll();file->close();QSqlRecord rec = tabModel->record(selModel->currentIndex().row());rec.setValue("photh", arr); //设置数据tabModel->setRecord(selModel->currentIndex().row(), rec); //设置行数据QPixmap pix;pix.load(aFile); //加载图片ui->label_10->setPixmap(pix.scaledToWidth(pix.width()));}
}void MainWindow::on_pushButton_6_clicked()
{QSqlRecord rec = tabModel->record(selModel->currentIndex().row());rec.setNull("photh");tabModel->setRecord(selModel->currentIndex().row(), rec);ui->label_10->clear();
}void MainWindow::on_pushButton_7_clicked()
{if (tabModel->rowCount() == 0)return;for (int i = 0; i < tabModel->rowCount(); ++i) {QSqlRecord rec = tabModel->record(i);rec.setValue("name", rec.value("name").toInt() + 100);tabModel->setRecord(i, rec);}if (tabModel->submitAll()) { // submit不成功,需要allQMessageBox::information(this, "成功", "涨工资成功");}
}void MainWindow::on_pushButton_8_clicked()
{bool ret = tabModel->submitAll();if (!ret) {QMessageBox::critical(this, "失败", "保存失败");}
}void MainWindow::on_pushButton_9_clicked()
{tabModel->revertAll(); //还原
}void MainWindow::on_comboBox_currentIndexChanged(int index)
{if (ui->radioButton->isChecked()) {tabModel->sort(index, Qt::AscendingOrder);} else {tabModel->sort(index, Qt::DescendingOrder);}tabModel->select();
}void MainWindow::on_radioButton_clicked()
{try {tabModel->sort(ui->comboBox->currentIndex(), Qt::AscendingOrder); // sort不需要select} catch (QException err) {qDebug() << err.what();}
}void MainWindow::on_radioButton_2_clicked()
{try {tabModel->sort(ui->comboBox->currentIndex(), Qt::DescendingOrder); // sort不需要select} catch (QException err) {qDebug() << err.clone();}
}void MainWindow::on_radioButton_3_clicked()
{tabModel->setFilter("name='12'");ui->statusbar->showMessage(QString("记录条数为 %1").arg(tabModel->rowCount()));
}void MainWindow::on_radioButton_4_clicked()
{tabModel->setFilter("name='张三'");ui->statusbar->showMessage(QString("记录条数为 %1").arg(tabModel->rowCount()));
}void MainWindow::on_radioButton_5_clicked()
{tabModel->setFilter("");ui->statusbar->showMessage(QString("记录条数为 %1").arg(tabModel->rowCount()));
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include "tcomboxdelegate.h"
#include <QDataWidgetMapper>
#include <QMainWindow>
#include <QSql>
#include <QSqlTableModel>
#include <QtSql>
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACEclass MainWindow : public QMainWindow {Q_OBJECTpublic:MainWindow(QWidget* parent = nullptr);~MainWindow();private slots:void on_pushButton_clicked();void do_current_changed(const QModelIndex& current, const QModelIndex& previous);void do_current_row_changed(const QModelIndex& current, const QModelIndex& previous);void on_pushButton_3_clicked();void on_pushButton_2_clicked();void on_pushButton_4_clicked();void on_pushButton_5_clicked();void on_pushButton_6_clicked();void on_pushButton_7_clicked();void on_pushButton_8_clicked();void on_pushButton_9_clicked();void on_comboBox_currentIndexChanged(int index);void on_radioButton_clicked();void on_radioButton_2_clicked();void on_radioButton_3_clicked();void on_radioButton_4_clicked();void on_radioButton_5_clicked();private:Ui::MainWindow* ui;QSqlTableModel* tabModel;QDataWidgetMapper* dataMapper;QItemSelectionModel* selModel;QSqlDatabase db;TComBoxDelegate delegateSex;TComBoxDelegate deleagteDepart;void openTable();
};
#endif // MAINWINDOW_H
tcomboxdelegate.cpp
#include "tcomboxdelegate.h"
#include <QComboBox>
TComBoxDelegate::TComBoxDelegate(QObject* parent): QStyledItemDelegate { parent }
{
}
QWidget* TComBoxDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{QComboBox* editor = new QComboBox(parent);editor->setEditable(m_editable);qDebug() << m_itemList.size();for (auto item : m_itemList) {editor->addItem(item);}return editor;
}void TComBoxDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const
{QComboBox* box = dynamic_cast<QComboBox*>(editor); //把editor转为指向QSpinBox的指针 动态强转QString value = index.model()->data(index, Qt::DisplayRole).toString();box->setCurrentText(value);
}void TComBoxDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{QComboBox* box = dynamic_cast<QComboBox*>(editor); //把editor转为指向QSpinBox的指针 动态强转QString value = box->currentText();model->setData(index, value);
}void TComBoxDelegate::updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& index) const
{editor->setGeometry(option.rect);
}void TComBoxDelegate::setItems(QStringList list, bool editabale)
{m_itemList = list;m_editable = editabale;
}
tcomboxdelegate.h
#ifndef TCOMBOXDELEGATE_H
#define TCOMBOXDELEGATE_H#include <QObject>
#include <QStyledItemDelegate>class TComBoxDelegate : public QStyledItemDelegate {Q_OBJECT
public:explicit TComBoxDelegate(QObject* parent = nullptr);// QAbstractItemDelegate interface
public:virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const override;virtual void setEditorData(QWidget* editor, const QModelIndex& index) const override;virtual void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const override;virtual void updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& index) const override;void setItems(QStringList list, bool editabale);private:QStringList m_itemList;bool m_editable;
};#endif // TCOMBOXDELEGATE_H
QSqlQueryModel模块使用
相关文章:

QT数据库编程
ui界面 mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" #include <QButtonGroup> #include <QFileDialog> #include <QMessageBox> MainWindow::MainWindow(QWidget* parent): QMainWindow(parent), ui(new Ui::M…...

基于stm32单片机的直流电机速度控制——LZW
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 目录 一、实验目的二、实验方法三、实验设计1.实验器材2.电路连接3.软件设计(1)实验变量(2)功能模块a)电机接收信号…...
实际项目中使用mockjs模拟数据
项目中的痛点 自己模拟的数据对代码的侵入程度太高,接口完成后要删掉对应的代码,导致接口开发完后端同事开发完,前端自己得加班;接口联调的时间有可能会延期,接口完成的质量参差不齐;对于数据量过大的模拟…...

【家庭公网IPv6】
家庭公网IPv6 这里有两个网站: 1、 IPV6版、多地Tcping、禁Ping版、tcp协议、tcping、端口延迟测试,在本机搭建好服务器后,可以用这个测试外网是否可以访问本机; 2、 IP查询ipw.cn,这个可以查询本机的网络是否IPv6访问…...

【iOS】Frame与Bounds的区别详解
iOS的坐标系 iOS特有的坐标是,是在iOS坐标系的左上角为坐标原点,往右为X正方向,向下为Y正方向。 bounds和frame都是属于CGRect类型的结构体,系统的定义如下,包含一个CGPoint(起点)和一个CGSiz…...

SpringBoot百货超市商城系统 附带详细运行指导视频
文章目录 一、项目演示二、项目介绍三、运行截图四、主要代码 一、项目演示 项目演示地址: 视频地址 二、项目介绍 项目描述:这是一个基于SpringBoot框架开发的百货超市系统。首先,这是一个很适合SpringBoot初学者学习的项目,代…...

【实践篇】推荐算法PaaS化探索与实践 | 京东云技术团队
作者:京东零售 崔宁 1. 背景说明 目前,推荐算法部支持了主站、企业业务、全渠道等20业务线的900推荐场景,通过梳理大促运营、各垂直业务线推荐场景的共性需求,对现有推荐算法能力进行沉淀和积累,并通过算法PaaS化打造…...

持续贡献开源力量,棱镜七彩加入openKylin
近日,棱镜七彩签署 openKylin 社区 CLA(Contributor License Agreement 贡献者许可协议),正式加入openKylin 开源社区。 棱镜七彩成立于2016年,是一家专注于开源安全、软件供应链安全的创新型科技企业。自成立以来&…...
Kafka的消费者如何管理偏移量?
在Kafka中,消费者可以通过管理和跟踪偏移量(offset)来确保消费者在消费消息时的准确性和可靠性。偏移量表示消费者在特定分区中已经消费的消息的位置。以下是几种常见的偏移量管理方式: 手动提交偏移量:消费者可以通过…...

IntelliJ IDEA流行的构建工具——Gradle
IntelliJ IDEA,是java编程语言开发的集成环境。IntelliJ在业界被公认为最好的java开发工具,尤其在智能代码助手、代码自动提示、重构、JavaEE支持、各类版本工具(git、svn等)、JUnit、CVS整合、代码分析、 创新的GUI设计等方面的功能可以说是超常的。 如…...

nacos源码打包及相关配置
nacos 本地下载后,需要 install 下: mvn clean install -Dmaven.test.skiptrue -Dcheckstyle.skiptrue -Dpmd.skiptrue -Drat.skiptruenacos源码修改后,重新打包生成压缩包命令:在 distribution 目录中运行: mvn -Pr…...

【机器学习】Multiple Variable Linear Regression
Multiple Variable Linear Regression 1、问题描述1.1 包含样例的X矩阵1.2 参数向量 w, b 2、多变量的模型预测2.1 逐元素进行预测2.2 向量点积进行预测 3、多变量线性回归模型计算损失4、多变量线性回归模型梯度下降4.1 计算梯度4.2梯度下降 首先,导入所需的库 im…...

自己创建的类,其他类中使用错误
说明:自己创建的类,在其他类中创建,报下面的错误(Cannot resolve sysmbol ‘Redishandler’); 解决:看下是不是漏掉了包名 加上包名,问题解决;...

Packet Tracer – 使用 TFTP 服务器升级思科 IOS 映像。
Packet Tracer – 使用 TFTP 服务器升级思科 IOS 映像。 地址分配表 设备 接口 IP 地址 子网掩码 默认网关 R1 F0/0 192.168.2.1 255.255.255.0 不适用 R2 G0/0 192.168.2.2 255.255.255.0 不适用 S1 VLAN 1 192.168.2.3 255.255.255.0 192.168.2.1 TFTP …...

并查集基础
一、概念及其介绍 并查集是一种树型的数据结构,用于处理一些不相交集合的合并及查询问题。 并查集的思想是用一个数组表示了整片森林(parent),树的根节点唯一标识了一个集合,我们只要找到了某个元素的的树根…...
C# 循环等知识点
《1》程序:事先写好的指令(代码) using 准备工具 namespace 模块名称 { class 子模块{ static void main()//具体事项 { 代码 } } } 《2》变量:内存里的一块空间,用来存储数据常用的有小数,整数,…...

1.1.2 SpringCloud 版本问题
目录 版本标识 版本类型 查看对应版本 版本兼容的权威——官网: 具体的版本匹配支持信息可以查看 总结 在将Spring Cloud集成到Spring Boot项目中时,确保选择正确的Spring Cloud版本和兼容性是非常重要的。由于Spring Cloud存在多个版本,因此…...

Android AIDL 使用
工程目录图 请点击下面工程名称,跳转到代码的仓库页面,将工程 下载下来 Demo Code 里有详细的注释 代码:LearnAIDL代码:AIDLClient. 参考文献 安卓开发学习之AIDL的使用android进阶-AIDL的基本使用Android AIDL 使用使用 AIDL …...
MongoDB——命令详解
db.fruit.remove({name:apple})//删除a为apple的记录db.fruit.remove({})//删除所有的记录db.fruit.remove()//报错 MongoDB使用及命令大全(一)_mongodb 删除命令_言不及行yyds的博客-CSDN博客...

机器学习深度学习——多层感知机的简洁实现
👨🎓作者简介:一位即将上大四,正专攻机器学习的保研er 🌌上期文章:机器学习&&深度学习——多层感知机的从零开始实现 📚订阅专栏:机器学习&&深度学习 希望文章对你…...
Vue记事本应用实现教程
文章目录 1. 项目介绍2. 开发环境准备3. 设计应用界面4. 创建Vue实例和数据模型5. 实现记事本功能5.1 添加新记事项5.2 删除记事项5.3 清空所有记事 6. 添加样式7. 功能扩展:显示创建时间8. 功能扩展:记事项搜索9. 完整代码10. Vue知识点解析10.1 数据绑…...

visual studio 2022更改主题为深色
visual studio 2022更改主题为深色 点击visual studio 上方的 工具-> 选项 在选项窗口中,选择 环境 -> 常规 ,将其中的颜色主题改成深色 点击确定,更改完成...

华为OD机试-食堂供餐-二分法
import java.util.Arrays; import java.util.Scanner;public class DemoTest3 {public static void main(String[] args) {Scanner in new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别while (in.hasNextLine()) { // 注意 while 处理多个 caseint a in.nextIn…...

Linux --进程控制
本文从以下五个方面来初步认识进程控制: 目录 进程创建 进程终止 进程等待 进程替换 模拟实现一个微型shell 进程创建 在Linux系统中我们可以在一个进程使用系统调用fork()来创建子进程,创建出来的进程就是子进程,原来的进程为父进程。…...
MySQL账号权限管理指南:安全创建账户与精细授权技巧
在MySQL数据库管理中,合理创建用户账号并分配精确权限是保障数据安全的核心环节。直接使用root账号进行所有操作不仅危险且难以审计操作行为。今天我们来全面解析MySQL账号创建与权限分配的专业方法。 一、为何需要创建独立账号? 最小权限原则…...

C++使用 new 来创建动态数组
问题: 不能使用变量定义数组大小 原因: 这是因为数组在内存中是连续存储的,编译器需要在编译阶段就确定数组的大小,以便正确地分配内存空间。如果允许使用变量来定义数组的大小,那么编译器就无法在编译时确定数组的大…...

免费PDF转图片工具
免费PDF转图片工具 一款简单易用的PDF转图片工具,可以将PDF文件快速转换为高质量PNG图片。无需安装复杂的软件,也不需要在线上传文件,保护您的隐私。 工具截图 主要特点 🚀 快速转换:本地转换,无需等待上…...
Java数值运算常见陷阱与规避方法
整数除法中的舍入问题 问题现象 当开发者预期进行浮点除法却误用整数除法时,会出现小数部分被截断的情况。典型错误模式如下: void process(int value) {double half = value / 2; // 整数除法导致截断// 使用half变量 }此时...

Vue ③-生命周期 || 脚手架
生命周期 思考:什么时候可以发送初始化渲染请求?(越早越好) 什么时候可以开始操作dom?(至少dom得渲染出来) Vue生命周期: 一个Vue实例从 创建 到 销毁 的整个过程。 生命周期四个…...
Kubernetes 网络模型深度解析:Pod IP 与 Service 的负载均衡机制,Service到底是什么?
Pod IP 的本质与特性 Pod IP 的定位 纯端点地址:Pod IP 是分配给 Pod 网络命名空间的真实 IP 地址(如 10.244.1.2)无特殊名称:在 Kubernetes 中,它通常被称为 “Pod IP” 或 “容器 IP”生命周期:与 Pod …...