Qt打印QStandardItemModel

时间:2017-01-23 06:13:47

标签: qt printing qprinter

我想打印" QStandardItemModel"的行。我使用这个代码,它工作,但表不漂亮。 我不知道如何调整行高,我也不知道如何根据表格第一行中单元格的宽度来设置列宽。

enter image description here

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();
    }
}

0 个答案:

没有答案