Reputation: 276
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!
Upvotes: 0
Views: 595
Reputation: 276
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.
Upvotes: 0
Reputation: 21514
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.
Upvotes: 1