如何使用Qt4打印到PNG格式

时间:2016-07-19 08:59:02

标签: c++ qt4

我正在努力使用Qt4将图像打印为PNG格式。 下面的代码具有PDF或PS的默认设置,但无法选择PNG:

void DetectorView::printToFile()
{

// A basic printing function
QPrinter printer;
QPrintDialog dialog(&printer, this);
if (dialog.exec()==QDialog::Accepted) {
    QPainter painter(&printer);
    this->render(&painter);
    std::cout << "INFO [DetectorView::printToFile] Wrote file " << std::endl;
}
else {
    std::cout << "INFO [DetectorView::printToFile] Cancelling printer " << std::endl;
}
}

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

使用此链接:Rendering QWidget to QImage loses alpha-channel,您可以将小部件呈现为QImage

然后,使用QImageWriter,您可以将其保存到png:

// render QWidget to QImage:
QImage bitmap(this->size(), QImage::Format_ARGB32);
bitmap.fill(Qt::transparent);
QPainter painter(&bitmap);
this->render(&painter, QPoint(), QRegion(), QWidget::DrawChildren);

// save QImage to png file:
QImageWriter writer("file.png", "png");
writer.write(bitmap);

注意:提供的链接适用于Qt5,但这适用于Qt4。

答案 1 :(得分:0)

使用jpo38的答案,我扩展到了我想要的行为:

void DetectorView::printToFile()
{
    QString default_name = "myImage.png";
    QImage bitmap(this->size(), QImage::Format_ARGB32);
    QPainter painter(&bitmap);
    this->render(&painter,QPoint(),QRegion(),QWidget::DrawChildren);
    QString filename = QFileDialog::getSaveFileName(this, tr("Save File"),QDir::homePath()+"/"+default_name,tr("Image Files (*.png *.jpg *.bmp)"));
    QImageWriter writer(filename, "png");
    writer.write(bitmap);
    std::cout << "INFO [DetectorView::printToFile] Wrote image to file" << std::endl;
}

请注意创建交互式窗口所需的QFileDialog。