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!
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.