Here's another approach in pure Qt:
Use QLocalServer and QLocalSocket to check for an application, and then use the signal slot mechanism to notify an 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 are using Qt 5.3 for Windows, there is an error for QWidget::setWindowFlags and Qt::WindowStaysOnTopHint , see https://bugreports.qt.io/browse/QTBUG-30359 .
source share