How I show application when open application again Qt

Here's another approach in pure Qt way:

Use QLocalServer and QLocalSocket to check the existence of application and then use signal-slot mechanism to notify the existing one.

#include "widget.h"
#include <QApplication>
#include <QObject>
#include <QLocalSocket>
#include <QLocalServer>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    const QString appKey = "applicationKey";

    QLocalSocket *socket = new QLocalSocket();
    socket->connectToServer(appKey);

    if (socket->isOpen()) {
        socket->close();
        socket->deleteLater();
        return 0;
    }
    socket->deleteLater();

    Widget w;
    QLocalServer server;

    QObject::connect(&server,
                     &QLocalServer::newConnection,
                     [&w] () {
        /*Set the window on the top level.*/
        w.setWindowFlags(w.windowFlags() |
                         Qt::WindowStaysOnTopHint);
        w.showNormal();
        w.setWindowFlags(w.windowFlags() &
                         ~Qt::WindowStaysOnTopHint
                         );
        w.showNormal();
        w.activateWindow();
    });
    server.listen(appKey);

    w.show();

    return a.exec();
}

But if you're using Qt 5.3 on Windows, there's a bug for QWidget::setWindowFlags and Qt::WindowStaysOnTopHint, see https://bugreports.qt.io/browse/QTBUG-30359.

Tags:

C++

Qt