Qt grab widget and save image

c++, qt

Solution

Here is the simplest way to save a widget as an image. This approach works on Qt 5:

ui->myWidget->grab().save("image.png");

Qt doc.:

- QPixmap QWidget::grab(const QRect &rectangle = QRect(QPoint(0, 0), QSize(-1, -1)))

- bool QPixmap::save(const QString &fileName, const char *format = nullptr, int quality = -1) const.

Problem

I have the following problem. I want to grab a widget and save it as an image. I want to save it as png, jpeg, and tiff. I have written the following code: ``` QString s = QFileDialog::getSaveFileName(this, "Save as", "Choose a filename", "PNG(*.png);; TIFF(*.tiff *.tif);; JPEG(*.jpg *.jpeg)"); std::string current_string = s.toLocal8Bit().constData(); //current_string = current_string + ".png"; char * buffer = new char[current_string.length()]; std::string temp = buffer; char* temp2 = &temp[0]; strcpy(buffer, current_string.c_str()); char* pch = strtok (temp2,"."); pch = strtok (NULL, "."); if(!QPixmap::grabWindow(m_widget->winId()).save(buffer,pch)) { QMessageBox::warning(this, "File could not be saved", "ok", QMessageBox::Ok); } ``` This works fine on my laptop. When I make a Visual Studio Setup it also works fine on my laptop, but when I install it on another pc, then the png format works fine (saves the right image), but jpeg and tif can't be saved. Then I tried it on a further pc, but there I tried it directly in Visual Studio with the project file. There I have all project settings like on my pc etc. and there jpeg and tif don't work. PNG works but it only saves a white image on that pc. Further I also tried there the installation file and its the same PNG = white image. Can anyone help me?

Original source

Related problems