Qt tableWidget 表格打印预览案例编码
时间: 2024-02-29 15:51:40 浏览: 187
Qt例子—打印和预览
4星 · 用户满意度95%
以下是一个基于 Qt 的 TableWidget 表格打印预览案例编码:
```cpp
#include <QtPrintSupport/QPrintDialog>
#include <QtPrintSupport/QPrinter>
#include <QtWidgets/QApplication>
#include <QtWidgets/QTableWidget>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QPushButton>
class TablePrinter : public QObject {
Q_OBJECT
public:
TablePrinter(QTableWidget *tableWidget, QObject *parent = nullptr) : QObject(parent), tableWidget(tableWidget) {}
void print() {
QPrinter printer(QPrinter::HighResolution);
printer.setPageSize(QPrinter::A4);
printer.setOrientation(QPrinter::Portrait);
QPrintDialog dialog(&printer, nullptr);
if (dialog.exec() == QDialog::Rejected) {
return;
}
QPainter painter(&printer);
painter.setRenderHint(QPainter::Antialiasing);
painter.setRenderHint(QPainter::TextAntialiasing);
int rowsPerPage = printer.pageRect().height() / tableWidget->rowHeight(0);
int totalRows = tableWidget->rowCount();
int totalPages = (totalRows + rowsPerPage - 1) / rowsPerPage;
for (int page = 1; page <= totalPages; ++page) {
painter.drawText(10, 10, QString("Page %1 of %2").arg(page).arg(totalPages));
int y = 50;
painter.drawLine(10, y, printer.pageRect().width() - 10, y);
y += 5;
int rowStart = (page - 1) * rowsPerPage;
int rowEnd = qMin(rowStart + rowsPerPage, totalRows);
for (int i = rowStart; i < rowEnd; ++i) {
int x = 10;
for (int j = 0; j < tableWidget->columnCount(); ++j) {
int colWidth = tableWidget->columnWidth(j);
painter.drawText(x, y, colWidth, tableWidget->rowHeight(i), Qt::AlignLeft | Qt::AlignVCenter,
tableWidget->item(i, j)->text());
x += colWidth;
}
y += tableWidget->rowHeight(i);
}
if (page < totalPages) {
printer.newPage();
}
}
}
private:
QTableWidget *tableWidget;
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QTableWidget tableWidget;
tableWidget.setColumnCount(3);
tableWidget.setRowCount(50);
tableWidget.setHorizontalHeaderLabels(QStringList() << "Name" << "Age" << "Gender");
for (int i = 0; i < 50; ++i) {
tableWidget.setItem(i, 0, new QTableWidgetItem(QString("Name %1").arg(i)));
tableWidget.setItem(i, 1, new QTableWidgetItem(QString::number(20 + i)));
tableWidget.setItem(i, 2, new QTableWidgetItem((i % 2 == 0) ? "Male" : "Female"));
}
QPushButton printButton("Print");
QObject::connect(&printButton, &QPushButton::clicked, [&tableWidget]() {
TablePrinter printer(&tableWidget);
printer.print();
});
QVBoxLayout layout;
layout.addWidget(&tableWidget);
layout.addWidget(&printButton);
QWidget widget;
widget.setLayout(&layout);
widget.show();
return app.exec();
}
```
在这个案例中,我们创建了一个包含 50 行 3 列的 TableWidget,并填充了一些数据。我们还创建了一个打印按钮,当用户点击该按钮时,会弹出一个打印对话框,用户可以选择打印机和打印选项。当用户确定打印后,程序会将表格分成多个页面,并逐页打印。每个页面都包含表格的一部分,并显示当前页数和总页数。
阅读全文