Yet another (maybe even better?) option is to use QPainter's powerful redirecting mechanism. This approach doesn't even require subclassing of QTableView.
if (dlg.
exec() == QDialog::Accepted) {
// calculate the total width/height table would need without scaling
const int rows = table->model()->rowCount();
const int cols = table->model()->columnCount();
double totalWidth = 0.0;
for (int c = 0; c < cols; ++c)
{
totalWidth += table->columnWidth(c);
}
double totalHeight = 0.0;
for (int r = 0; r < rows; ++r)
{
totalHeight += table->rowHeight(r);
}
// redirect table's painting on a pixmap
QPixmap pixmap
(totalWidth, totalHeight
);
QPainter::setRedirected(table
->viewport
(),
&pixmap
);
QPainter::restoreRedirected(table
->viewport
());
// print scaled pixmap
painter.drawPixmap(printer.pageRect(), pixmap, pixmap.rect());
}
QPrinter printer(QPrinter::HighResolution);
QPrintDialog dlg(&printer, this);
if (dlg.exec() == QDialog::Accepted)
{
// calculate the total width/height table would need without scaling
const int rows = table->model()->rowCount();
const int cols = table->model()->columnCount();
double totalWidth = 0.0;
for (int c = 0; c < cols; ++c)
{
totalWidth += table->columnWidth(c);
}
double totalHeight = 0.0;
for (int r = 0; r < rows; ++r)
{
totalHeight += table->rowHeight(r);
}
// redirect table's painting on a pixmap
QPixmap pixmap(totalWidth, totalHeight);
QPainter::setRedirected(table->viewport(), &pixmap);
QPaintEvent event(QRect(0, 0, totalWidth, totalHeight));
QApplication::sendEvent(table->viewport(), &event);
QPainter::restoreRedirected(table->viewport());
// print scaled pixmap
QPainter painter(&printer);
painter.drawPixmap(printer.pageRect(), pixmap, pixmap.rect());
}
To copy to clipboard, switch view to plain text mode
Bookmarks