qt tablewidget 实现分页功能_Qt数据库与QTableWidget结合的增删改查
时间: 2024-02-17 15:04:13 浏览: 291
Qt中的tablewidget 通过分页方式加载大量数据
3星 · 编辑精心推荐
实现QTableWidget的分页功能,可以在QTableWidget下方添加一个QComboBox选择页码,以及上一页和下一页按钮进行翻页。具体步骤如下:
1. 创建QTableWidget和分页控制控件(QComboBox和QPushButton)
```cpp
ui->tableWidget->setColumnCount(2);
ui->tableWidget->setHorizontalHeaderLabels(QStringList() << "ID" << "Name");
// 分页控件
ui->comboBox->addItems(QStringList() << "10" << "20" << "50" << "100");
ui->pushButton_prev->setEnabled(false);
ui->pushButton_next->setEnabled(false);
```
2. 绑定分页控制事件,例如选择每页显示条数,上一页和下一页按钮事件
```cpp
connect(ui->comboBox, QOverload<int>::of(&QComboBox::activated), [=](int index) {
pageSize = ui->comboBox->currentText().toInt();
currentPage = 1;
refreshTable();
});
connect(ui->pushButton_prev, &QPushButton::clicked, [=]() {
if (currentPage > 1) {
currentPage--;
refreshTable();
}
});
connect(ui->pushButton_next, &QPushButton::clicked, [=]() {
if (currentPage < totalPages) {
currentPage++;
refreshTable();
}
});
```
3. 实现刷新表格的函数refreshTable()
```cpp
void MainWindow::refreshTable()
{
int rowCount = ui->tableWidget->rowCount();
for (int i = rowCount - 1; i >= 0; i--) {
ui->tableWidget->removeRow(i);
}
QSqlDatabase db = QSqlDatabase::database();
QSqlQuery query(db);
query.exec(QString("SELECT COUNT(*) FROM mytable"));
query.next();
int totalRows = query.value(0).toInt();
totalPages = (totalRows + pageSize - 1) / pageSize;
ui->label_totalPages->setText(QString("of %1").arg(totalPages));
ui->pushButton_prev->setEnabled(currentPage > 1);
ui->pushButton_next->setEnabled(currentPage < totalPages);
int offset = (currentPage - 1) * pageSize;
QString sql = QString("SELECT * FROM mytable LIMIT %1, %2").arg(offset).arg(pageSize);
query.exec(sql);
int row = 0;
while (query.next()) {
ui->tableWidget->insertRow(row);
for (int col = 0; col < ui->tableWidget->columnCount(); col++) {
QTableWidgetItem *item = new QTableWidgetItem(query.value(col).toString());
ui->tableWidget->setItem(row, col, item);
}
row++;
}
}
```
4. 在需要刷新表格的地方调用refreshTable()函数即可
至于Qt数据库与QTableWidget结合的增删改查操作,可以使用QSqlTableModel或者手动执行SQL查询语句,具体实现可以参考前面的回答。
阅读全文