代码拉取完成,页面将自动刷新
#include "showaandp.h"
#include "mainshow.h"
#include <QtSql/QSqlQuery>
#include <QDebug>
#include <QtSql/QSqlError>
#include <QtSql/QSqlRecord>
#include <QTableWidgetItem>
#include <QtSql/QSqlDatabase>
ShowAandP::ShowAandP(QWidget *parent)
: QMainWindow(parent)
{
setupUi(this);
createConnection();
// 连接按钮的点击事件到槽函数
connect(searchButton, &QPushButton::clicked, this, &ShowAandP::on_searchButton_clicked);
// 连接用户类型选择变化的信号到槽函数
connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ShowAandP::on_userTypeChanged);
// 初始化表格数据
on_userTypeChanged(comboBox->currentIndex());
}
ShowAandP::~ShowAandP()
{
db.close();
}
void ShowAandP::createConnection()
{
// 创建并打开数据库连接
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("test.db"); // 替换为数据库文件名
if (!db.open()) {
qDebug() << "无法连接到数据库:" << db.lastError().text();
}
}
void ShowAandP::on_searchButton_clicked()
{
// 获取用户选择的类型和搜索条件
QString userType = comboBox->currentText();
QString username = usernameBox->text().trimmed();
QString name = nameBox->text().trimmed();
QString department = departmentBox->text().trimmed();
QString tableName = (userType == "医生") ? "DOCTOR" : "PATIENT";
if(userType=="医生")
{
this->label_3->show();
this->departmentBox->show();
}
else
{
this->label_3->hide();
this->departmentBox->hide();
}
// 构建 SQL 查询条件
QString queryStr = QString("SELECT * FROM %1 WHERE 1=1").arg(tableName);
if (!username.isEmpty()) {
queryStr += QString(" AND username LIKE '%%1%'").arg(username);
}
if (!name.isEmpty()) {
queryStr += QString(" AND name LIKE '%%1%'").arg(name);
}
if (userType == "医生" && !department.isEmpty()) {
queryStr += QString(" AND department LIKE '%%1%'").arg(department);
}
// 执行查询
QSqlQuery query(db);
if (!query.exec(queryStr)) {
qDebug() << "查询失败:" << query.lastError().text();
return;
}
// 获取查询结果
QSqlRecord record = query.record();
int columnCount = record.count();
// 设置列数和列标题
tableWidget->setColumnCount(columnCount);
QStringList headers;
for (int i = 0; i < columnCount; ++i) {
headers << record.fieldName(i);
}
tableWidget->setHorizontalHeaderLabels(headers);
// 填充数据
tableWidget->setRowCount(0); // 先清空之前的数据
int rowCount = 0;
while (query.next()) {
tableWidget->insertRow(rowCount);
for (int i = 0; i < columnCount; ++i) {
QTableWidgetItem *item = new QTableWidgetItem(query.value(i).toString());
tableWidget->setItem(rowCount, i, item);
}
++rowCount;
}
tableWidget->setRowCount(rowCount); // 更新行数
}
void ShowAandP::on_userTypeChanged(int index)
{
Q_UNUSED(index);
on_searchButton_clicked(); // 自动触发搜索按钮的功能以刷新表格
}
void ShowAandP::on_searchButton_2_clicked()
{
this->close();
MainShow *ms = new MainShow;
ms->setAttribute(Qt::WA_DeleteOnClose);
ms->show();
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。