Qt抓取小部件并保存图像

时间:2013-05-03 15:11:52

标签: c++ qt

我有以下问题。我想抓取一个小部件并将其保存为图像。我想把它保存为png,jpeg和tiff。我写了以下代码:

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

这在我的笔记本电脑上工作正常。当我进行Visual Studio安装时它在我的笔记本电脑上工作正常,但是当我在另一台电脑上安装它时,png格式工作正常(保存正确的图像),但jpeg和tif无法保存。然后我在另一台电脑上试了一下,但是我在Visual Studio中直接用项目文件试了一下。在那里,我有所有项目设置,如在我的电脑等,有jpeg和TIF不起作用。 PNG可以工作,但它只在白色图像上保存白色图像。此外,我还尝试了安装文件及其相同的PNG =白色图像。

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:8)

这是将窗口小部件另存为图像的最简单方法。这种方法适用于Qt 5:

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

答案 1 :(得分:1)

插件不直接进入应用程序EXE文件夹,而是应用程序文件夹下的“plugins”文件夹。我相信,我还必须将它放在“imageformats”文件夹而不是“插件”中至少一次。这可能是一个不同的平台/特殊构建。

有关Windows的信息,请参阅此Qt deployment guide

此外,您的“新char []”调用可能最终会崩溃。您需要为空字符保留空间:

char * buffer = new char[current_string.length() + 1];

另外,您不需要所有std :: string内容来获得扩展名。随着时间的推移,这可能会令人沮丧。

QString saveFilename = QFileDialog::getSaveFileName(this, "Save as", "Choose a filename", "PNG(*.png);; TIFF(*.tiff *.tif);; JPEG(*.jpg *.jpeg)");

QString saveExtension = "PNG";
int pos = saveFilename.lastIndexOf('.');
if (pos >= 0)
    saveExtension = saveFilename.mid(pos + 1);

if(!QPixmap::grabWidget(m_widget).save(saveFilename, qPrintable(saveExtension)))
{
    // since you have a widget, just use grabWidget() here. winId() would possibly have
    // portability issues on other platforms.  qPrintable(saveExtension) is effectively
    // the same as saveExtension.toLocal8Bit().constData()

    QMessageBox::warning(this, "File could not be saved", "ok", QMessageBox::Ok);
}