Qt窗体存成图片

1、基本操作

QPixmap pm = this->grab();
pm.save("111.jpg");

只截取了当前显示的部分进行存储,未显示部分没有

2、存储QTableWidget

如果是表格,往往行数过多就会导致有些行数被隐藏掉了,可以通过将窗体高度增加的形式来存储【实际上还是只存储了显示区域】

void Measure::_createImgReport(QTableWidget *pTable)
{
    if(!pTable){
        ZLOG_ERROR()<<"table is null"<<LINE_COUNT<<FILE_NAME;
        return;
    }

    QWidget* pWidget = new QWidget;
    QVBoxLayout* layout = new QVBoxLayout;

    QFont serifFont("Times", 20, QFont::Bold);

    QLabel* lel = new QLabel(pWidget);                      //标题
    lel->setAlignment(Qt::AlignCenter);
    lel->setText("通信等效功能测试设备测试报告:");
    lel->setFont(serifFont);


    QTableWidget* pnewTable = new QTableWidget(pWidget);     //表格
    pnewTable->setColumnCount(5);

    pnewTable->verticalHeader()->setVisible(false);

    QStringList header;
    header<<" 序号 "<<"测试流程"<<"合格判断"<<"实测值"<<"测试结果";
    pnewTable->setHorizontalHeaderLabels(header);

#if 1
    pnewTable->setColumnWidth(VALUE_0, TABLE_COLUM_MIN_WIDTH);
    pnewTable->horizontalHeader()->setSectionResizeMode(VALUE_1, QHeaderView::Stretch);
    pnewTable->horizontalHeader()->setSectionResizeMode(VALUE_2, QHeaderView::Stretch);
    pnewTable->horizontalHeader()->setSectionResizeMode(VALUE_3, QHeaderView::Stretch);
    pnewTable->setColumnWidth(VALUE_4, TABLE_COLUM_MIN_WIDTH);
    pnewTable->resizeColumnsToContents();
    pnewTable->resizeRowsToContents();
    pnewTable->setWordWrap(true);
#endif
    for(int i=0; i<pTable->rowCount(); i++){
        QCheckBox* cb = static_cast<QCheckBox*>(pTable->cellWidget(i, 0));

        if(!cb) continue;
        if(cb->isChecked()){
            int row = pnewTable->rowCount();
            pnewTable->insertRow(row);

            if(pTable->item(i,1)){
                pnewTable->setItem(row, 0, new QTableWidgetItem(pTable->item(i, 1)->text()));
            }
            if(pTable->item(i,2)){
                pnewTable->setItem(row, 1, new QTableWidgetItem(pTable->item(i, 2)->text()));
            }
            if(pTable->item(i,3)){
                pnewTable->setItem(row, 2, new QTableWidgetItem(pTable->item(i, 3)->text()));
            }
            if(pTable->item(i,4)){
                pnewTable->setItem(row, 3, new QTableWidgetItem(pTable->item(i, 4)->text()));
            }
            QWidget* wd = static_cast<QWidget*>(pTable->cellWidget(i, 5));
            if(!wd) continue;
            pnewTable->setItem(row, 4, new QTableWidgetItem(wd->toolTip()));
        }
    }

    pWidget->resize(this->width(), (pnewTable->rowCount()+3)*30);  //根据表格函数来设置当前窗口的显示高度,避免图片显示不全

    layout->addWidget(lel);
    layout->addWidget(pnewTable);

    pWidget->setLayout(layout);

    QPixmap pm = pWidget->grab();
#if 1
    QString csvPath = CSV_DIR + QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss-zzz") + ".jpg";
    pm.save(csvPath);
#endif

    pWidget->close();
    pWidget->deleteLater();
}

 

posted @ 2021-03-29 18:44  朱小勇  阅读(836)  评论(0编辑  收藏  举报