Search code examples
qt4

How can I start application in background, i.e. without showing GUI?


I'm using Qt for taking screenshots (screen printing).

QPixmap::grabWindow(QApplication::desktop()->winId());

I'd like the application to start in background, i.e. I want it to be hidden when it starts (or even run in console mode).
How can I do that in Qt?


Solution

  • As I understand, you need an app that, when executed, doesn't show a widget (UI) and runs in the background.

    One way to achieve this is to launch the app and show an icon in System tray instead of showing a dialog/window on the screen.

    You can code this something like this:

    // main.cpp
    
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
    
        // this is the important bit
        app.setQuitOnLastWindowClosed(false);
        
        // Say "Window" is your class which inherits QWidget or QDialog or QMainWindow
        Window window;
        // Don't call window.show()
        // Setup and invoke system tray icon in the constructor
    
        return app.exec();
    }
    

    There are a few other things you'd need to set. You can refer to the System Tray Icon Example for that.


    Update 2022:
    If you are looking for a way to invoke the app using a global shortcut you might wanna look into options other than Qxt, as libqxt is no longer maintained and might not work with newer versions of Qt.