How I show application when open application again Qt

前端 未结 2 1648
闹比i
闹比i 2021-01-19 02:06

Now, I have 1 application, but I don\'t want to open application twice, so I using QShareMemory to detect application when open twice. And my question is: how I

相关标签:
2条回答
  • 2021-01-19 02:34

    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.

    0 讨论(0)
  • 2021-01-19 02:59

    Just use QSingleApplication class instead of QApplication: https://github.com/qtproject/qt-solutions/tree/master/qtsingleapplication

    int main(int argc, char **argv)
    {
        QtSingleApplication app(argc, argv);
        if (app.isRunning())
            return 0;
    
        MyMainWidget mmw;
        app.setActivationWindow(&mmw);
        mmw.show();
    
        return app.exec();
    }
    

    It is part of Qt Solutions: https://github.com/qtproject/qt-solutions

    0 讨论(0)
提交回复
热议问题