PDA

View Full Version : Print QStandardItemModel



neda
31st January 2017, 05:49
I want to print rows of "QStandardItemModel". I use this code, It works but table is not beautiful. I don't know how to adjust row height and I don't know how to set column widths based on the width of cells in the first row of the table.


QPrinter printer;
printer.setPageSize(QPrinter::A4);
printer.setFullPage(true);

QPrintDialog *dlg = new QPrintDialog(&printer,0);
if(dlg->exec() == QDialog::Accepted) {

QPainter painter;
if (painter.begin(&printer)) {

painter.translate(0,0);

int position = 0;
int rowCount=newMyModel->rowCount(QModelIndex());

for(int r=0;r<rowCount;r++)
{
if( position > painter.window().height()-100 )
{
printer.newPage();

position = 0;
painter.resetTransform();
painter.translate(0, 0);
}

QString html="<table style='page-break-after:always' border='1' width='100%' cellpadding =10 style='border-width: 1px;border-style: solid;border-color: #9e9e9e;width:100%'>";

index=newMyModel->index(r, 0);

QVariant prop1=index.data(MyModel::prop1);
QVariant prop2=index.data(MyModel::prop2);

'''
'''
'''

html.append(
"<tr style='background-color:red'>"
"<td style='border-width: 1px;padding:10; border-style: solid; border-color: #9e9e9e;width:16%'>"+prop1.toString()+" </td>"
"<td style='border-width: 1px;padding:10; border-style: solid; border-color: #9e9e9e;width:16%'>"+prop2.toString()+" </td>"
...
...
...);

}

html.append("</table>");

QRect rect = painter.boundingRect(painter.window(),
Qt::AlignJustify | Qt::TextWordWrap,
html);
QTextDocument doc;
doc.setHtml(html);
doc.drawContents(&painter, rect);

painter.drawRect(rect);
painter.translate(0, rect.height());
position += rect.height();
}
painter.end();
}
}

And I use this code but it does not work (Print blank page).


QPrinter printer;
printer.setPageSize(QPrinter::A4);
printer.setFullPage(true);

QPrintDialog *dlg = new QPrintDialog(&printer,0);
if(dlg->exec() == QDialog::Accepted) {

QTableView* pTableView = new QTableView;
pTableView->setModel(newMyModel);

int width = 0;
int height = 0;
int columns = newMyModel->columnCount();
int rows = newMyModel->rowCount();

pTableView->resizeColumnsToContents();

for( int i = 0; i < columns; ++i ) {
width += pTableView->columnWidth(i);
}

for( int i = 0; i < rows; ++i ) {
height += pTableView->rowHeight(i);
}

pTableView->setFixedSize(width, height);
pTableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOf f);
pTableView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff) ;

pTableView->render(&printer);