PDA

View Full Version : How to print a QTableView



teikchuan
27th March 2009, 05:35
Hi,

I would like to print a table which contains text only. I search through the forum and found this piece of code



QPainter painter(printer);
const QRect area = printer->pageRect();
const int rows = m_data_model.rowCount();
const int cols = m_data_model.columnCount();

// calculate the total width/height table would need without scaling
double totalWidth = 0.0;
for (int c = 0; c < cols; ++c)
{
totalWidth += columnWidth(c);
}
double totalHeight = 0.0;
for (int r = 0; r < rows; ++r)
{
totalHeight += rowHeight(r);
}

// paint cells
for (int r = 0; r < rows; ++r)
{
for (int c = 0; c < cols; ++c)
{
QModelIndex idx = m_data_model.index(r, c);
QStyleOptionViewItem option = viewOptions();
option.rect = visualRect(idx);
itemDelegate()->paint(&painter, option, idx);
}
}


However, the code does not print the table's vertical and horizontal headers, as well as the grid lines. How can I print a table, with both the headers and the grid lines?

I am using Qt4.4.

Thanks.

teikchuan
3rd April 2009, 08:05
Now, I am able to print the horizontal header with the code below:



const int horizontal_height = horizontalHeader()->height();
const int vertical_width = verticalHeader()->width();
int width = horizontal_header_rect.size().width();

QWidget *view_port = horizontalHeader()->viewport();
QPixmap horizontal_pixmap(width, horizontal_height);
QPaintEvent paint_horizontal_event(horizontal_header_rect);
dc->setRedirected(view_port, &horizontal_pixmap);
QApplication::sendEvent(view_port, &paint_horizontal_event);
dc->restoreRedirected(view_port);
dc->drawPixmap(printer->pageRect().topLeft() + QPoint(vertical_width, 0), horizontal_pixmap, horizontal_header_rect);


It could print nicely but, I still face a problem if the header is larger than the paper size. For example, I have a table with 33 columns. I could print nicely the header for the first 20 columns in first page, but fails to print for the remaining 13 columns in second page.

How could I modify the code to print the header nicely for the second page and all subsequent pages? Could any gurus out there helps?

Thanks.