qt tableb view 打印预览和打印的问题 个人解决办法

来源:互联网 发布:编码器编程程序接线图 编辑:程序博客网 时间:2024/05/21 21:40

                    好了长话短说  因为tableview 不提供print 函数 ,所以 要实现打印现在基本是基于 两种  一种是利用render 函数    一种是利用 html 来实现    我个人因为在用render方法的时候 打印预览是空白的  (同事使用相同的代码,在qt4.8+vs2008可以实现) 所以使用了html 来实现  。OK贴代码

// 打印预览 

QPrinterprinter(QPrinter::ScreenResolution);

    QPrintPreviewDialog preview(&printer);
    connect(&preview, SIGNAL(paintRequested(QPrinter *)),this,SLOT(print(QPrinter* )));
    preview.exec();//打印QString strStream,strTitle;
    QTextStream out(&strStream);
    strTitle="carman——feng";
    const int rowCount = ui->tableView->model()->rowCount();
    const int columnCount = ui->tableView->model()->columnCount();
    out <<  "<html>\n"
            "<head>\n"
            "<meta Content=\"Textml; charset=Windows-1251\">\n"
         <<  QString("<title>%1</title>\n").arg(strTitle)
          <<  "</head>\n"
              "<body bgcolor=#ffffff link=#5000A0>\n"
              "<table border=1 cellspacing=0 cellpadding=2>\n";
    // headers
    out << "<thead><tr bgcolor=#f0f0f0>";
    for (int column = 0; column < columnCount; ++column)
        if (!ui->tableView->isColumnHidden(column))
            out << QString("<th>%1</th>").arg(ui->tableView->model()->headerData(column, Qt::Horizontal).toString());
    out << "</tr></thead>\n";
    // data table
    for (int row = 0; row < rowCount; ++row)
    {
        out << "<tr>";
        for (int column = 0; column < columnCount; ++column)
        {
            if (!ui->tableView->isColumnHidden(column)) {
                QString data = ui->tableView->model()->data(ui->tableView->model()->index(row, column)).toString().simplified();
                out << QString("<td bkcolor=0>%1</td>").arg((!data.isEmpty()) ? data : QString("&nbsp;"));
            }
        }
        out << "</tr>\n";
    }
    out <<  "</table>\n"
            "</body>\n"
            "<ml>\n";
    QTextDocument *document = new QTextDocument();
    document->setHtml(strStream);
    document->print(printer);

html的方法在qt 5.5 \5.6 版本的minGW 测试 可行

0 0
原创粉丝点击