0

I'm struggling to print an image to the PNG format using Qt4. The code below has default settings of either PDF or PS, but no way to choose 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;
}
}

Any help would be appreciated!

jwsmithers
  • 276
  • 2
  • 5
  • 15
  • Does this really need to make use of `QPrintDialog`? Why not just render to a `QImage` and then use [`QImage::save`](http://doc.qt.io/qt-5/qimage.html#save)? – G.M. Jul 19 '16 at 09:19

2 Answers2

1

Using this link: Rendering QWidget to QImage loses alpha-channel, you can render your widget to a QImage.

Then, using QImageWriter, you can save it to a 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);

Note: links provided are for Qt5, but this should work with Qt4.

Community
  • 1
  • 1
jpo38
  • 20,821
  • 10
  • 70
  • 151
  • This does work, but not really the behaviour I was looking for. There needs to be an interactive GUI where you can change file names and locations. Still, thanks! It helped me get my solution which I'll post below – jwsmithers Jul 19 '16 at 11:15
  • That's really a detail, as you proposed, just use `QFileDialog::getSaveFileName` to pickup file name. – jpo38 Jul 19 '16 at 11:46
0

Using jpo38's answer, I expanded to get the behaviour I wanted:

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

Note the QFileDialog which is needed to create the interactive window.

jwsmithers
  • 276
  • 2
  • 5
  • 15