当前位置: 首页 > news >正文

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

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 目录 一、实验目的二、实验方法三、实验设计1.实验器材2.电路连接3.软件设计&#xff08;1&#xff09;实验变量&#xff08;2&#xff09;功能模块a&#xff09;电机接收信号…...

实际项目中使用mockjs模拟数据

项目中的痛点 自己模拟的数据对代码的侵入程度太高&#xff0c;接口完成后要删掉对应的代码&#xff0c;导致接口开发完后端同事开发完&#xff0c;前端自己得加班&#xff1b;接口联调的时间有可能会延期&#xff0c;接口完成的质量参差不齐&#xff1b;对于数据量过大的模拟…...

【家庭公网IPv6】

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

【iOS】Frame与Bounds的区别详解

iOS的坐标系 iOS特有的坐标是&#xff0c;是在iOS坐标系的左上角为坐标原点&#xff0c;往右为X正方向&#xff0c;向下为Y正方向。 bounds和frame都是属于CGRect类型的结构体&#xff0c;系统的定义如下&#xff0c;包含一个CGPoint&#xff08;起点&#xff09;和一个CGSiz…...

SpringBoot百货超市商城系统 附带详细运行指导视频

文章目录 一、项目演示二、项目介绍三、运行截图四、主要代码 一、项目演示 项目演示地址&#xff1a; 视频地址 二、项目介绍 项目描述&#xff1a;这是一个基于SpringBoot框架开发的百货超市系统。首先&#xff0c;这是一个很适合SpringBoot初学者学习的项目&#xff0c;代…...

【实践篇】推荐算法PaaS化探索与实践 | 京东云技术团队

作者&#xff1a;京东零售 崔宁 1. 背景说明 目前&#xff0c;推荐算法部支持了主站、企业业务、全渠道等20业务线的900推荐场景&#xff0c;通过梳理大促运营、各垂直业务线推荐场景的共性需求&#xff0c;对现有推荐算法能力进行沉淀和积累&#xff0c;并通过算法PaaS化打造…...

持续贡献开源力量,棱镜七彩加入openKylin

近日&#xff0c;棱镜七彩签署 openKylin 社区 CLA&#xff08;Contributor License Agreement 贡献者许可协议&#xff09;&#xff0c;正式加入openKylin 开源社区。 棱镜七彩成立于2016年&#xff0c;是一家专注于开源安全、软件供应链安全的创新型科技企业。自成立以来&…...

Kafka的消费者如何管理偏移量?

在Kafka中&#xff0c;消费者可以通过管理和跟踪偏移量&#xff08;offset&#xff09;来确保消费者在消费消息时的准确性和可靠性。偏移量表示消费者在特定分区中已经消费的消息的位置。以下是几种常见的偏移量管理方式&#xff1a; 手动提交偏移量&#xff1a;消费者可以通过…...

IntelliJ IDEA流行的构建工具——Gradle

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

nacos源码打包及相关配置

nacos 本地下载后&#xff0c;需要 install 下&#xff1a; mvn clean install -Dmaven.test.skiptrue -Dcheckstyle.skiptrue -Dpmd.skiptrue -Drat.skiptruenacos源码修改后&#xff0c;重新打包生成压缩包命令&#xff1a;在 distribution 目录中运行&#xff1a; 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梯度下降 首先&#xff0c;导入所需的库 im…...

自己创建的类,其他类中使用错误

说明&#xff1a;自己创建的类&#xff0c;在其他类中创建&#xff0c;报下面的错误&#xff08;Cannot resolve sysmbol ‘Redishandler’&#xff09;&#xff1b; 解决&#xff1a;看下是不是漏掉了包名 加上包名&#xff0c;问题解决&#xff1b;...

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 …...

并查集基础

一、概念及其介绍 并查集是一种树型的数据结构&#xff0c;用于处理一些不相交集合的合并及查询问题。 并查集的思想是用一个数组表示了整片森林&#xff08;parent&#xff09;&#xff0c;树的根节点唯一标识了一个集合&#xff0c;我们只要找到了某个元素的的树根&#xf…...

C# 循环等知识点

《1》程序&#xff1a;事先写好的指令&#xff08;代码&#xff09; using 准备工具 namespace 模块名称 { class 子模块{ static void main()//具体事项 { 代码 } } } 《2》变量&#xff1a;内存里的一块空间&#xff0c;用来存储数据常用的有小数&#xff0c;整数&#xff0c…...

1.1.2 SpringCloud 版本问题

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

Android AIDL 使用

工程目录图 请点击下面工程名称&#xff0c;跳转到代码的仓库页面&#xff0c;将工程 下载下来 Demo Code 里有详细的注释 代码&#xff1a;LearnAIDL代码&#xff1a;AIDLClient. 参考文献 安卓开发学习之AIDL的使用android进阶-AIDL的基本使用Android AIDL 使用使用 AIDL …...

MongoDB——命令详解

db.fruit.remove({name:apple})//删除a为apple的记录db.fruit.remove({})//删除所有的记录db.fruit.remove()//报错 MongoDB使用及命令大全(一&#xff09;_mongodb 删除命令_言不及行yyds的博客-CSDN博客...

机器学习深度学习——多层感知机的简洁实现

&#x1f468;‍&#x1f393;作者简介&#xff1a;一位即将上大四&#xff0c;正专攻机器学习的保研er &#x1f30c;上期文章&#xff1a;机器学习&&深度学习——多层感知机的从零开始实现 &#x1f4da;订阅专栏&#xff1a;机器学习&&深度学习 希望文章对你…...

eNSP-Cloud(实现本地电脑与eNSP内设备之间通信)

说明&#xff1a; 想象一下&#xff0c;你正在用eNSP搭建一个虚拟的网络世界&#xff0c;里面有虚拟的路由器、交换机、电脑&#xff08;PC&#xff09;等等。这些设备都在你的电脑里面“运行”&#xff0c;它们之间可以互相通信&#xff0c;就像一个封闭的小王国。 但是&#…...

深入浅出Asp.Net Core MVC应用开发系列-AspNetCore中的日志记录

ASP.NET Core 是一个跨平台的开源框架&#xff0c;用于在 Windows、macOS 或 Linux 上生成基于云的新式 Web 应用。 ASP.NET Core 中的日志记录 .NET 通过 ILogger API 支持高性能结构化日志记录&#xff0c;以帮助监视应用程序行为和诊断问题。 可以通过配置不同的记录提供程…...

K8S认证|CKS题库+答案| 11. AppArmor

目录 11. AppArmor 免费获取并激活 CKA_v1.31_模拟系统 题目 开始操作&#xff1a; 1&#xff09;、切换集群 2&#xff09;、切换节点 3&#xff09;、切换到 apparmor 的目录 4&#xff09;、执行 apparmor 策略模块 5&#xff09;、修改 pod 文件 6&#xff09;、…...

汽车生产虚拟实训中的技能提升与生产优化​

在制造业蓬勃发展的大背景下&#xff0c;虚拟教学实训宛如一颗璀璨的新星&#xff0c;正发挥着不可或缺且日益凸显的关键作用&#xff0c;源源不断地为企业的稳健前行与创新发展注入磅礴强大的动力。就以汽车制造企业这一极具代表性的行业主体为例&#xff0c;汽车生产线上各类…...

React Native在HarmonyOS 5.0阅读类应用开发中的实践

一、技术选型背景 随着HarmonyOS 5.0对Web兼容层的增强&#xff0c;React Native作为跨平台框架可通过重新编译ArkTS组件实现85%以上的代码复用率。阅读类应用具有UI复杂度低、数据流清晰的特点。 二、核心实现方案 1. 环境配置 &#xff08;1&#xff09;使用React Native…...

定时器任务——若依源码分析

分析util包下面的工具类schedule utils&#xff1a; ScheduleUtils 是若依中用于与 Quartz 框架交互的工具类&#xff0c;封装了定时任务的 创建、更新、暂停、删除等核心逻辑。 createScheduleJob createScheduleJob 用于将任务注册到 Quartz&#xff0c;先构建任务的 JobD…...

STM32标准库-DMA直接存储器存取

文章目录 一、DMA1.1简介1.2存储器映像1.3DMA框图1.4DMA基本结构1.5DMA请求1.6数据宽度与对齐1.7数据转运DMA1.8ADC扫描模式DMA 二、数据转运DMA2.1接线图2.2代码2.3相关API 一、DMA 1.1简介 DMA&#xff08;Direct Memory Access&#xff09;直接存储器存取 DMA可以提供外设…...

DBAPI如何优雅的获取单条数据

API如何优雅的获取单条数据 案例一 对于查询类API&#xff0c;查询的是单条数据&#xff0c;比如根据主键ID查询用户信息&#xff0c;sql如下&#xff1a; select id, name, age from user where id #{id}API默认返回的数据格式是多条的&#xff0c;如下&#xff1a; {&qu…...

OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别

OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别 直接训练提示词嵌入向量的核心区别 您提到的代码: prompt_embedding = initial_embedding.clone().requires_grad_(True) optimizer = torch.optim.Adam([prompt_embedding...

项目部署到Linux上时遇到的错误(Redis,MySQL,无法正确连接,地址占用问题)

Redis无法正确连接 在运行jar包时出现了这样的错误 查询得知问题核心在于Redis连接失败&#xff0c;具体原因是客户端发送了密码认证请求&#xff0c;但Redis服务器未设置密码 1.为Redis设置密码&#xff08;匹配客户端配置&#xff09; 步骤&#xff1a; 1&#xff09;.修…...