drug_sensitivity_reaction/michistoricalrecords.cpp

807 lines
27 KiB
C++
Raw Permalink Normal View History

2025-07-17 08:39:15 +08:00
#include "michistoricalrecords.h"
#include "ui_michistoricalrecords.h"
#include <QStandardItemModel>
#include<QMessageBox>
#include<QGraphicsDropShadowEffect>
#include<QPainter>
#include<QPainter>
#include <QAxObject>
michistoricalrecords::michistoricalrecords(QWidget *parent) :
QWidget(parent),
ui(new Ui::michistoricalrecords)
{
ui->setupUi(this);
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectItems);
ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
ui->tableView->setAlternatingRowColors(true);
model = new CheckBoxTableModel(this);
model->setTable("micjishu");//鎵撳紑鏁版嵁搴撲腑鍚嶄负鈥溾€濈殑琛?
model->select();
ui->tableView->setModel(model);
ui->tableView->show();
theSelection=new QItemSelectionModel(model);//鍏宠仈閫夋嫨妯″瀷
// 设置第一列的复选框初始状态
for (int i = 0; i < model->rowCount(); ++i) {
QModelIndex index = model->index(i, 0);
model->setData(index, Qt::Unchecked, Qt::CheckStateRole);
}
// 连接信号槽,当复选框状态改变时选中整行
connect(model, &CheckBoxTableModel::dataChanged, this, &michistoricalrecords::onDataChanged);
// // 设置选中行的背景颜色为浅蓝色,即使失去焦点也保持颜色
// ui->tableView->setStyleSheet(
// "QTableView::item:selected {"
// " background-color: lightblue;" // 选中项的背景颜色
// " color: black;" // 选中项的文字颜色
// "}"
// "QTableView {"
// " selection-background-color: lightblue;" // 选中行的背景颜色
// " selection-color: black;" // 选中行的文字颜色
// "}"
// );
// 启用整行选择模式,允许多行选中
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableView->setSelectionMode(QAbstractItemView::MultiSelection);
// 连接点击信号
connect(ui->tableView, &QTableView::clicked, this, &michistoricalrecords::onTableViewClicked);
// 设置自定义表头
header = new CheckBoxHeader(Qt::Horizontal, ui->tableView);
ui->tableView->setHorizontalHeader(header);
connect(header, &CheckBoxHeader::checkStateChanged, this, &michistoricalrecords::onHeaderCheckStateChanged);
//theSelection褰撳墠椤瑰彉鍖栨椂瑙﹀彂currentChanged淇″彿
connect(theSelection,SIGNAL(currentChanged(QModelIndex,QModelIndex)),
this,SLOT(on_currentChanged(QModelIndex,QModelIndex)));
ui->tableView->setSelectionModel(theSelection); //璁剧疆閫夋嫨妯″瀷
ui->tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
shuaxin();
//鍒涘缓鐣岄潰缁勪欢涓庢暟鎹ā鍨嬬殑瀛楁涔嬮棿鐨勬暟鎹槧灏?
dataMapper= new QDataWidgetMapper();
dataMapper->setModel(model);//璁剧疆鏁版嵁妯″瀷
dataMapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
m_maxtu=new maxtu;
// connect(this, SIGNAL(yuan(QPixmap)),m_maxtu, SLOT(getyuan(QPixmap)));
connect(this, SIGNAL(lujing(QString,QString)),m_maxtu, SLOT(getlujing(QString,QString)));
ui->pushButton->setFixedSize(73,34);
ui->pushButton_2->setFixedSize(73,34);
ui->pushButton_4->setFixedSize(73,34);
ui->lineEdit_3->setFixedSize(117,25);
ui->lineEdit_4->setFixedSize(117,25);
ui->frame->setFixedSize(170,37);
ui->frame_2->setFixedSize(170,37);
ui->comboBox->setFixedSize(170,37);
ui->comboBox_2->setFixedSize(170,37);
ui->comboBox_3->setFixedSize(170,37);
ui->tableView->setItemDelegateForColumn(6, &delegate);
ui->tableView->setItemDelegateForColumn(7, &delegate);
ui->tableView->setShowGrid(false);
ui-> tableView->verticalHeader()->setVisible(false);
//ui->widget_3->setFixedHeight(80);
QTimer *timer;
timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, [=](){
QDateTime dateTime= QDateTime::currentDateTime();//鑾峰彇绯荤粺褰撳墠鐨勬椂闂?
QString str = dateTime .toString("yyyy-MM-dd hh:mm:ss");//鏍煎紡鍖栨椂闂?
// ui->label_7->setText(str);
});
timer->start(1000);
this->setWindowFlags(Qt::FramelessWindowHint); // 闅愯棌鏍囬鏍?
ui->tableView->setItemDelegateForColumn(9,delegate2);
connect(delegate2, &ButtonDelegate5::editButtonClicked, this, &michistoricalrecords::chakan);
connect(delegate2, &ButtonDelegate5::deleteButtonClicked, this, &michistoricalrecords::shanchu);
m_look=new look;
connect(this, &michistoricalrecords::cha, m_look, &look::getcha);
// connect(this, SIGNAL(cha(QString)), m_look, SLOT(getcha(QString)));
getshui();
ui->tableView->setShowGrid(false);
ui->tableView->setFixedSize(1730,760);
ui->tableView->setFixedWidth(1730);
ui->tableView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
connect(ui->tableView, &QTableView::clicked, this, &michistoricalrecords::onCellClicked);
m_date=new date;
connect(m_date,SIGNAL(kaishi(QString)), this, SLOT(getkaishi(QString)));
m_datee=new datee;
connect(m_datee,SIGNAL(kaishi(QString)), this, SLOT(getkaishii(QString)));
QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect(this);
//设置阴影距离
shadow->setOffset(0, 0);
//设置阴影颜色
shadow->setColor(QColor(214, 214, 214));
//设置阴影圆角
shadow->setBlurRadius(30);
//给嵌套QWidget设置阴影
ui->frame_3->setFixedSize(1755,907);
ui->frame_3->setGraphicsEffect(shadow);
CenteredItemDelegate* delegate = new CenteredItemDelegate();
ui->tableView->setItemDelegate(delegate);
for (int i=1;i<=10 ;i++ ) {
ui->tableView->setColumnWidth(i,183);
}
ui->tableView->setColumnWidth(0,80);
ui->tableView->columnWidth(173);
ui->tableView->horizontalHeader()->setFixedHeight(40);
connect(m_maxtu,&maxtu::guanmeng,this,[=](){mask_window.close();});
connect(m_look,&look::guanmeng,this,[=](){mask_window.close();});
ui->lineEdit_2->setFixedSize(56,32);
QWidget *buttonContainer = new QWidget(this);
buttonLayout = new QHBoxLayout(buttonContainer);
ui->scrollArea ->setWidget(buttonContainer);
ui-> scrollArea->setWidgetResizable(true);
buttonGroup = new QButtonGroup(this);
totalPages = (model->rowCount() + recordsPerPage - 1) / recordsPerPage;
ui->scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
updateButtons();
}
michistoricalrecords::~michistoricalrecords()
{
delete ui;
}
void michistoricalrecords::onDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
if (topLeft.column() == 0) {
bool checked = model->data(topLeft, Qt::CheckStateRole).toBool();
if (checked) {
// 选中整行
ui->tableView->selectRow(topLeft.row());
} else {
// 取消当前行的选中状态
QItemSelectionModel *selectionModel = ui->tableView->selectionModel();
selectionModel->select(topLeft, QItemSelectionModel::Deselect | QItemSelectionModel::Rows);
}
}
}
void michistoricalrecords::onTableViewClicked(const QModelIndex &index)
{
// 如果点击的是第一列,直接返回
if (index.column() == 0) {
return;
}
// 获取复选框索引
QModelIndex checkBoxIndex = model->index(index.row(), 0);
// 切换复选框状态
bool isChecked = model->data(checkBoxIndex, Qt::CheckStateRole).toBool();
model->setData(checkBoxIndex, !isChecked ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole);
// 确保整行选择状态与复选框状态一致
if (!isChecked) {
ui->tableView->selectRow(index.row());
} else {
ui->tableView->selectionModel()->select(index, QItemSelectionModel::Deselect | QItemSelectionModel::Rows);
}
}
void michistoricalrecords::onHeaderCheckStateChanged(Qt::CheckState state)
{
model->setAllCheckState(state);
if (state == Qt::Checked) {
for (int i = 0; i < model->rowCount(); ++i) {
ui->tableView->selectRow(i);
ui->tableView->selectAll();
}
} else {
ui->tableView->clearSelection();
}
}
void michistoricalrecords::getshuaxin()
{
qDebug()<<"鍒锋柊浜?";
QTimer::singleShot(100,this,[=](){shuaxin();}) ;
}
void michistoricalrecords::chakan(const QModelIndex& index)
{
QAbstractItemModel* model = ui->tableView->model();
if (model) {
int row = index.row();
int col = index.column();
QVariant data = model->data(index);
if (data.isValid()) {
QString dataStr = data.toString();
emit cha(dataStr);
qDebug() << "缂栬緫鎸夐挳琚偣鍑伙紝琛?: " << row << " 鍒?: " << col << " 鏁版嵁: " << dataStr;
} else {
qDebug() << "缂栬緫鎸夐挳琚偣鍑伙紝琛?: " << row << " 鍒?: " << col << " 瀵瑰簲鍗曞厓鏍兼棤鏁版嵁";
}
}
mask_window.setWindowOpacity(0.2);
//设置窗体的背景色,这里的百分比就是透明度
mask_window.setStyleSheet("background-color: black;");
mask_window.setGeometry(0, 0, 1920,1080); //获取父窗体的几何形状设置当前窗口
mask_window.setWindowFlags(Qt::FramelessWindowHint); // 隐藏标题栏
//对话框
mask_window.show();
m_look->show();
}
void michistoricalrecords::getshui()
{
ui->comboBox->clear();
ui->comboBox_2->clear();
ui->comboBox_3->clear();
QString queryString = QString("SELECT name FROM junshu");
QSqlQuery mquery;
if (!mquery.exec(queryString)) {
}
while (mquery.next()) {
QVariant value = mquery.value(0);
QString str=value.toString();
ui->comboBox->addItem(str);
}
QString queryString2 = QString("SELECT id FROM junshu");
QSqlQuery mquery2;
if (!mquery2.exec(queryString2)) {
}
while (mquery2.next()) {
QVariant value = mquery2.value(0);
QString str=value.toString();
ui->comboBox_3->addItem(str);
}
}
void michistoricalrecords::shanchu(const QModelIndex& index)
{
int result = QMessageBox::information(NULL, "提示", "确定要删除本行内容吗", QMessageBox::Ok | QMessageBox::Cancel);
if (result == QMessageBox::Ok) {
qDebug() << "删除按钮被点击,行: " << index.row() << " 列: " << index.column();
if (model->removeRow(index.row())) {
if (model->submitAll()) {
shuaxin(); // 重置视图,强制刷新界面显示
} else {
}
} else {
}
}
}
void michistoricalrecords::shuaxin()
{
model->setTable("micjishu");
ui->tableView->setModel(model);
model->select();
model->setHeaderData(0, Qt::Horizontal, "序号");
model->setHeaderData(1, Qt::Horizontal, "项目名称");
model->setHeaderData(2, Qt::Horizontal, "药敏板序列号");
model->setHeaderData(3, Qt::Horizontal, "生产批号");
model->setHeaderData(4, Qt::Horizontal, "菌属");
model->setHeaderData(5, Qt::Horizontal, "菌种");
model->setHeaderData(6, Qt::Horizontal, "原始图片");
model->setHeaderData(7, Qt::Horizontal, "判读图片");
model->setHeaderData(8, Qt::Horizontal, "时间");
model->setHeaderData(9, Qt::Horizontal, "判读结果");
for (int i=0;i<=model->rowCount() ;i++ ) {
ui->tableView->setRowHeight(i,40);
}
for (int i=1;i<=10 ;i++ ) {
ui->tableView->setColumnWidth(i,183);
}
ui->tableView->setColumnWidth(0,80);
// 计算总页数并更新分页按钮
totalPages = (model->rowCount() + recordsPerPage - 1) / recordsPerPage;
QString s = "" + QString::number(totalPages) + "";
ui->label_7->setText(s);
}
void michistoricalrecords::on_pushButton_clicked()
{
if (ui->lineEdit_3->text() == "" || ui->lineEdit_4->text() == "") {
// 如果时间输入框为空,执行原来的查询逻辑
QSqlQuery query;
QString str = QString("SELECT * FROM micjishu WHERE xiangcheng LIKE '%1%' AND junshu LIKE '%2%' AND junzhong LIKE '%3%'")
.arg(ui->comboBox_3->currentText())
.arg(ui->comboBox->currentText())
.arg(ui->comboBox_2->currentText());
qDebug() << str;
query.prepare(str);
if (query.exec()) {
model->setQuery(query); // 使用已有的model避免创建新的QSqlQueryModel
ui->tableView->setModel(model);
ui->tableView->show();
model->setHeaderData(0, Qt::Horizontal, "序号");
model->setHeaderData(1, Qt::Horizontal, "项目名称");
model->setHeaderData(2, Qt::Horizontal, "药敏板序列号");
model->setHeaderData(3, Qt::Horizontal, "生产批号");
model->setHeaderData(4, Qt::Horizontal, "菌属");
model->setHeaderData(5, Qt::Horizontal, "菌种");
model->setHeaderData(6, Qt::Horizontal, "原始图片");
model->setHeaderData(7, Qt::Horizontal, "判读图片");
model->setHeaderData(8, Qt::Horizontal, "时间");
model->setHeaderData(9, Qt::Horizontal, "判读结果");
// 计算总页数并更新分页按钮
totalPages = (model->rowCount() + recordsPerPage - 1) / recordsPerPage;
QString s = "" + QString::number(totalPages) + "";
ui->label_7->setText(s);
for (int i = 0; i <= model->rowCount(); i++) {
ui->tableView->setRowHeight(i, 40);
}
updateButtons();
} else {
qDebug() << "Query failed:" << query.lastError().text();
}
} else {
// 如果时间输入框不为空,增加时间段内的检索条件
QSqlQuery query;
QString str = QString("SELECT * FROM micjishu WHERE xiangcheng LIKE '%1%' AND junshu LIKE '%2%' AND junzhong LIKE '%3%' AND time BETWEEN '%4' AND '%5'")
.arg(ui->comboBox_3->currentText())
.arg(ui->comboBox->currentText())
.arg(ui->comboBox_2->currentText())
.arg(ui->lineEdit_4->text()) // 开始时间
.arg(ui->lineEdit_3->text()); // 结束时间
qDebug() << str;
query.prepare(str);
if (query.exec()) {
model->setQuery(query); // 使用已有的model避免创建新的QSqlQueryModel
ui->tableView->setModel(model);
ui->tableView->show();
model->setHeaderData(0, Qt::Horizontal, "序号");
model->setHeaderData(1, Qt::Horizontal, "项目名称");
model->setHeaderData(2, Qt::Horizontal, "药敏板序列号");
model->setHeaderData(3, Qt::Horizontal, "生产批号");
model->setHeaderData(4, Qt::Horizontal, "菌属");
model->setHeaderData(5, Qt::Horizontal, "菌种");
model->setHeaderData(6, Qt::Horizontal, "原始图片");
model->setHeaderData(7, Qt::Horizontal, "判读图片");
model->setHeaderData(8, Qt::Horizontal, "时间");
model->setHeaderData(9, Qt::Horizontal, "判读结果");
// 计算总页数并更新分页按钮
totalPages = (model->rowCount() + recordsPerPage - 1) / recordsPerPage;
QString s = "" + QString::number(totalPages) + "";
ui->label_7->setText(s);
for (int i = 0; i <= model->rowCount(); i++) {
ui->tableView->setRowHeight(i, 40);
}
updateButtons();
} else {
qDebug() << "Query failed:" << query.lastError().text();
}
}
}
//导出
void michistoricalrecords::on_pushButton_2_clicked()
{
// 安全检查
if (!this || !ui || !ui->tableView) {
qDebug() << "UI components not initialized";
return;
}
QStringList customHeaders = {
"序号", "项目名称", "药敏板序号", "生产批号", "菌属", "菌种",
"氟康唑"," ", "伊曲康唑"," ", "伏立康唑"," ", "泊沙康唑"," ", "艾沙康唑"," ", "卡泊芬净"," ",
"米卡芬净", " ","氟胞嘧啶"," ", "阿尼芬净"," ", "两性霉素B"," ", "时间",
};
QAbstractItemModel *model = ui->tableView->model();
if (!model) {
QMessageBox::warning(this, "导出失败", "表格模型未初始化");
return;
}
QItemSelectionModel *selectionModel = ui->tableView->selectionModel();
QModelIndexList selectedRows = selectionModel->selectedRows();
if (selectedRows.isEmpty()) {
QMessageBox::warning(this, "导出失败", "未选中任何行。");
return;
}
QString filePath = QFileDialog::getSaveFileName(this, "Export to CSV", "", "CSV Files (*.csv)");
if (filePath.isEmpty()) {
return;
}
QFile file(filePath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::warning(this, "导出失败", "无法创建文件: " + file.errorString());
return;
}
QTextStream out(&file);
out.setEncoding(QStringConverter::Utf8);
out.setGenerateByteOrderMark(true);
// 写入表头
out << customHeaders.join(",") << "\n";
// 处理数据行
for (const QModelIndex &index : selectedRows) {
if (!index.isValid()) continue;
int row = index.row();
QStringList dataRow;
QString ninthColumnData;
for (int col = 0; col < model->columnCount(); ++col) {
if (col == 6 || col == 7) { // 跳过第七列和第八列
continue;
}
else if (col == 8) { // 处理第九列数据
QModelIndex currentIndex = model->index(row, col);
if (!currentIndex.isValid()) continue;
QVariant data = model->data(currentIndex, Qt::DisplayRole);
ninthColumnData = data.toString().replace(",", ";");
}
else if (col == 9) { // 处理CSV文件
QModelIndex currentIndex = model->index(row, col);
if (!currentIndex.isValid()) continue;
QString csvPath = model->data(currentIndex, Qt::DisplayRole).toString();
if (csvPath.isEmpty()) {
file.close();
QFile::remove(filePath); // 删除已创建的部分文件
QMessageBox::warning(this, "导出失败",
"" + QString::number(row + 1) + "行的CSV文件为空导出失败");
return; // 直接终止导出过程
}
QFile csvFile(csvPath);
if (!csvFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
file.close();
QFile::remove(filePath); // 删除已创建的部分文件
QMessageBox::warning(this, "导出失败",
"" + QString::number(row + 1) + "行的CSV文件读取失败导出失败");
return; // 直接终止导出过程
}
QTextStream csvIn(&csvFile);
csvIn.setEncoding(QStringConverter::Utf8);
QStringList lines = csvIn.readAll().split('\n');
csvFile.close();
// for (int lineIdx = 1; lineIdx < lines.size() && (lineIdx - 1) < 10; ++lineIdx) {
// QStringList csvCols = lines[lineIdx].split(',');
// QString col4 = csvCols.size() > 3 ? csvCols[3] : "";
// QString col5 = csvCols.size() > 4 ? csvCols[4] : "";
// dataRow.append(QString("%1(%2)").arg(col4).arg(col5));
// }
// while (dataRow.size() - col < 10) {
// dataRow.append("");
// }
// }
// else {
// QModelIndex currentIndex = model->index(row, col);
// if (!currentIndex.isValid()) continue;
// QVariant data = model->data(currentIndex, Qt::DisplayRole);
// dataRow.append(data.toString().replace(",", ";"));
// }
// }
// dataRow.insert(16, ninthColumnData);
// while (dataRow.size() < customHeaders.count()) {
// dataRow.append("");
// }
// out << dataRow.join(",") << "\n";
// }
// file.close();
// QMessageBox::information(this, "导出成功", "数据已成功导出到: " + filePath);
// 修改这里:将 col4 和 col5 分开存储,各占一个单元格
for (int lineIdx = 1; lineIdx < lines.size() && (lineIdx - 1) < 10; ++lineIdx) {
QStringList csvCols = lines[lineIdx].split(',');
QString col4 = csvCols.size() > 3 ? csvCols[3] : "";
QString col5 = csvCols.size() > 4 ? csvCols[4] : "";
// 先添加 col4
dataRow.append(col4);
// 然后添加 col5
dataRow.append(col5);
}
// 确保有足够的空单元格
while (dataRow.size() - col < 20) { // 10对(col4,col5)需要20个单元格
dataRow.append("");
}
}
else {
QModelIndex currentIndex = model->index(row, col);
if (!currentIndex.isValid()) continue;
QVariant data = model->data(currentIndex, Qt::DisplayRole);
dataRow.append(data.toString().replace(",", ";"));
}
}
dataRow.insert(26, ninthColumnData);
while (dataRow.size() < customHeaders.count()) {
dataRow.append("");
}
out << dataRow.join(",") << "\n";
}
file.close();
QMessageBox::information(this, "导出成功", "数据已成功导出到: " + filePath);
}
void michistoricalrecords::on_pushButton_4_clicked()
{
shuaxin();
// 重新计算总页数
totalPages = (model->rowCount() + recordsPerPage - 1) / recordsPerPage;
updatePage();
updateButtons();
}
void michistoricalrecords::onCellClicked(const QModelIndex &index) {
if (index.column() == 6 || index.column() == 7) {
int curRecNo = index.row();
QSqlRecord curRec = model->record(curRecNo);
QString yuanshi = curRec.value("yuanshi").toString();
QString jieguo = curRec.value("jieguo").toString();
emit lujing(yuanshi, jieguo);
mask_window.setWindowOpacity(0.2);
mask_window.setStyleSheet("background-color: black;");
mask_window.setGeometry(0, 0, 1920, 1080);
mask_window.setWindowFlags(Qt::FramelessWindowHint);
mask_window.show();
m_maxtu->setWindowModality(Qt::ApplicationModal);
m_maxtu->show();
}
}
void michistoricalrecords::on_pushButton_3_clicked()
{
emit fanhui();
}
void michistoricalrecords::on_comboBox_currentTextChanged(const QString &arg1)
{
ui->comboBox_2->clear();
QString sql=QString("select name from junzhong where shuname='%1'").arg(arg1);
qDebug()<<sql;
QSqlQuery mquery;
if (!mquery.exec(sql)) {
}
while (mquery.next()) {
QVariant value = mquery.value(0);
ui->comboBox_2->addItem(value.toString());
}
}
void michistoricalrecords::on_toolButton_3_clicked()
{
}
void michistoricalrecords::on_toolButton_clicked()
{
int result = QMessageBox::information(NULL, "提示", "确定要退出运行吗", QMessageBox::Ok| QMessageBox::Cancel);
if (result == QMessageBox::Ok) {
emit guan2();
emit tuichu2();
QTimer::singleShot(500,this,[=](){qApp->quit();
}) ;
}
}
void michistoricalrecords::on_pushButton_5_clicked()
{
m_date->move(880,180);
m_date->exec();
}
void michistoricalrecords::on_pushButton_6_clicked()
{
m_datee->move(880,180);
m_datee->exec();
}
void michistoricalrecords::getkaishi(QString str)
{
ui->lineEdit_4->setText(str);
}
void michistoricalrecords::getkaishii(QString str)
{
ui->lineEdit_3->setText(str);
}
void michistoricalrecords::updatePage()
{
if (model) {
int startIndex = (currentPage - 1) * recordsPerPage;
int endIndex = std::min(startIndex + recordsPerPage, model->rowCount());
for (int i = 0; i < model->rowCount(); ++i) {
ui->tableView->setRowHidden(i, i < startIndex || i >= endIndex);
}
for (int i=0;i<=model->rowCount() ;i++ ) {
ui->tableView->setRowHeight(i,40);
}
for (int i=1;i<=10 ;i++ ) {
ui->tableView->setColumnWidth(i,183);
}
ui->tableView->setColumnWidth(0,80);
}
}
void michistoricalrecords::updateButtons()
{
QLayoutItem *item;
while ((item = buttonLayout->takeAt(0)) != nullptr) {
delete item->widget();
delete item;
}
int startPage = std::max(1, currentPage - 4); // 计算起始页
int endPage = std::min(totalPages, startPage + 9); // 计算结束页
// 确保当前页在第五个位置
if (endPage - startPage < 9 && currentPage - 4 > 0) {
startPage = std::max(1, currentPage - (9 - (endPage - startPage)));
endPage = std::min(totalPages, startPage + 9);
}
int buttonCount = 0; // 用于记录按钮个数
for (int i = startPage; i <= endPage; i++) {
QPushButton *button = new QPushButton(QString::number(i), this);
buttonLayout->addWidget(button);
buttonGroup->addButton(button, i);
// 设置当前页按钮样式
if (i == currentPage) {
button->setStyleSheet("QPushButton {color:rgb(0, 170, 255); }");
} else {
button->setStyleSheet("");
}
buttonCount++;
// 连接按钮点击信号到槽函数
connect(button, &QPushButton::clicked, this, [=]() {
currentPage = i;
updatePage();
updateButtons(); // 更新按钮样式
});
}
// 根据按钮个数设置 scrollArea 的宽度
if (buttonCount >= 1 && buttonCount <= 10) {
ui->scrollArea->setFixedWidth(buttonCount * 40);
}
}
void michistoricalrecords::onPageButtonClicked(int id) {
currentPage = id;
qDebug()<<id;
updatePage();
}
void michistoricalrecords::on_pushButton_10_clicked()
{
if (currentPage > 1) {
currentPage--;
updatePage();
updateButtons();
} else {
qDebug() << "已经是第一页,无法继续上一页操作";
}
}
void michistoricalrecords::on_pushButton_9_clicked()
{
if (currentPage < totalPages - 1) {
currentPage++;
updatePage();
updateButtons();
} else {
qDebug() << "已经是最后一页,无法继续下一页操作";
}
}
void michistoricalrecords::on_pushButton_11_clicked()
{
bool ok;
int page = ui->lineEdit_2->text().toInt(&ok);
if (ok) {
// 页码从 1 开始,所以减 1 转换为从 0 开始的索引
int targetPage = page;
if (targetPage >= 0 && targetPage <= totalPages) {
currentPage = targetPage;
updatePage();
updateButtons();
} else {
qDebug() << "输入的页码超出范围,请输入 1 到 " << totalPages << " 之间的页码";
}
} else {
qDebug() << "输入的页码不合法,请输入一个有效的数字";
}
}