简体   繁体   English

使用 Qt C++ 截屏

[英]Take screenshot with Qt C++

I'm trying to take a screenshot with my application.我正在尝试使用我的应用程序截取屏幕截图。 But I get the following error message :但我收到以下错误消息:

QPixmap: Must construct a QGuiApplication before a QPixmap

My program runs in the background and I do not want a GUI.我的程序在后台运行,我不想要 GUI。 How would I create a "QGuiApplication" and then hide the window permanently ?我将如何创建“QGuiApplication”然后永久隐藏窗口? Or is there another way to take a screenshot without having to create a GUI ?或者是否有另一种无需创建 GUI 即可截取屏幕截图的方法?

I was using the following code to take the screenshot :我使用以下代码截取屏幕截图:

QScreen *screen;
QPixmap qpx_pixmap;

screen = QGuiApplication::primaryScreen();
qpx_pixmap = screen->grabWindow(0);
screenshotTarget = dir.path() + "/" + QDateTime::currentDateTime().toString("dddd hh:mm:ss");
qpx_pixmap.save(screenshotTarget);

Create an instance of QGuiApplication on startup, before you create your QPixmap .创建QPixmap之前,在启动时创建QGuiApplication的实例。 You don't need to also create a GUI.您也不需要创建 GUI。 QGuiApplication itself will not create any windows or anything visible. QGuiApplication本身不会创建任何窗口或任何可见的东西。

A good place for that is at the start of main() :一个很好的地方是在main()的开头:

int main(int argc, char* argv[])
{
    QGuiApplication app(argc, argv);

    // ...

It also works with QApplication , since it inherits from QGuiApplication .它也适用于QApplication ,因为它继承自QGuiApplication It just provides extra things needed for creating QWidget based objects, which you don't need.它只是提供了创建基于QWidget的对象所需的额外东西,而您不需要这些东西。 The important thing is that the QGuiApplication object is created before the QPixmap .重要的是QGuiApplication对象是QPixmap之前创建的。

Finally, you need tell grabWindow() which part to grab.最后,您需要告诉grabWindow()抓取哪个部分。 To grab the whole screen, use:要抓取整个屏幕,请使用:

auto geom = screen->geometry();
qpx_pixmap = screen->grabWindow(0, geom.x(), geom.y(), geom.width(), geom.height());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM