5

我正在尝试通过 QWebView 创建报告,通过 QPrintPreviewDialog 显示并打印它。假设我想创建一个 100 行的表,分成几页,并将当前行号添加到每页的页脚(我实际任务的抽象变体)。我的代码:

    void MainWindow::preview(){
    QPrinter printer;
    printer.setPageSize(QPrinter::A4);
    printer.setOrientation(QPrinter::Portrait);
    printer.setPageMargins(10,10,10,10,QPrinter::Millimeter);

    QPrintPreviewDialog print_preview(&printer, this);
    print_preview.setWindowState(Qt::WindowMaximized);
    connect(&print_preview, SIGNAL(paintRequested(QPrinter*)), this, SLOT(paint_pages(QPrinter*)));
    print_preview.exec();
}

void MainWindow::paint_pages(QPrinter *printer){
    QList<QWebView*> pages;
    QWebView *current = 0;
    QPainter painter(printer);
    int i = 0;
    while(i <= 100){
        current = new QWebView();
        pages << current;
        i = populate_web(current, printer, i);
    }
    int pc = pages.count();
    for(i = 0; i < pc; i++){
        if(i != 0) printer->newPage();
        pages.at(i)->render(&painter);
    }
    for(i = 0; i < pc; i++)
        delete pages.at(i);
}


int MainWindow::populate_web(QWebView *pg, QPrinter *printer, int n){
    QString html = "<html><body>";
    html += "<table cellspacing=0 border = 1 style='border-collapse: collapse'>";
    int page_height = printer->paperRect(QPrinter::Point).height();
    for(++n; n <= 100; n++){
        html += QString("<tr><td width=200>%1</td><td width=200>%2</td><td width=300>%3</td></tr>").arg(n).arg(n*n).arg(n*n*n);
        QString html2 = html + "</table></body></html>";
        pg->setHtml(html2);
        int content_height = pg->page()->mainFrame()->contentsSize().height();
        if(content_height + 20 > page_height){
            html += "</table>";
            html += QString("<p>Current value: %1</p>").arg(n);
            break;
        }
    }
    if(n > 100) html += "</table>";
    html += "</body></html>";

    pg->setHtml(html);
    return n;
}

所以,我希望得到整张纸上的表格,除了 10 毫米的边距。但不是它,我得到了一些奇怪的东西(图片在这里);更重要的是 - 滚动条不会出现在第一页上,只是从第二页开始。我该怎么做才能用我的表格填充整个页面并从滚动条释放页面?

4

1 回答 1

1

After line:

html += "</body></html>";

Add this line:

pg->setFixedSize(QSize(printer->width(),printer->height()));
于 2014-09-05T07:04:59.297 回答