Search code examples
c++qtscreenshot

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. How would I create a "QGuiApplication" and then hide the window permanently ? Or is there another way to take a screenshot without having to create a 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);

Solution

  • Create an instance of QGuiApplication on startup, before you create your QPixmap. You don't need to also create a GUI. QGuiApplication itself will not create any windows or anything visible.

    A good place for that is at the start of main():

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

    It also works with QApplication, since it inherits from QGuiApplication. It just provides extra things needed for creating QWidget based objects, which you don't need. The important thing is that the QGuiApplication object is created before the QPixmap.

    Finally, you need tell grabWindow() which part to grab. To grab the whole screen, use:

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