首页 > 解决方案 > 如果应用程序已经打开,则聚焦打开的应用程序窗口,同时再次单击应用程序图标

问题描述

我对pyqt很陌生。我正在开发应用程序。我做了基本的应用程序,我正在使用以下代码来防止应用程序多次打开

''' Class to check weather app is already open or not '''
class SingleApplication(QtWidgets.QApplication):
    messageAvailable = QtCore.pyqtSignal(object)

    def __init__(self, argv, key):
        super().__init__(argv)
        # cleanup (only needed for unix)
        QtCore.QSharedMemory(key).attach()
        self._memory = QtCore.QSharedMemory(self)
        self._memory.setKey(key)
        if self._memory.attach():
            self._running = True
        else:
            self._running = False
            if not self._memory.create(1):
                raise RuntimeError(self._memory.errorString())

    def isRunning(self):
        return self._running



if __name__ == '__main__':

    key = common.appTitle
    app = SingleApplication(sys.argv,key)
    print(app.isRunning())
    if app.isRunning():
        print("App is already running")
        sys.exit(1)
    else:
        appctxt = ApplicationContext()       # 1. Instantiate ApplicationContext
        window = Mainwindow()

        QApplication.setQuitOnLastWindowClosed(False) ## prevent to close while close message box at the time of background running
        mainwindow = window.runwindow()
        mainwindow.show()

        exit_code = appctxt.app.exec_()      # 2. Invoke appctxt.app.exec_()
        sys.exit(exit_code)

上面的代码防止了应用程序的多次打开。如果我们打开多个应用程序,它会使用“应用程序已在运行”的日志消息来阻止。如果应用程序已经处于打开状态,我需要在单击应用程序图标时聚焦或激活已打开的应用程序窗口。请指导我。谢谢

标签: pythonpython-3.xpyqtpyqt5

解决方案


最简单的方法是使用QLocalServerQLocalSocket,它允许创建本地连接并在应用程序之间进行通信,但在这种情况下,检查服务器是否已经存在或在尝试新连接时收到通知就足够了:

from PyQt5 import QtCore, QtNetwork, QtWidgets

class UniqueApplication(QtWidgets.QApplication):
    anotherInstance = QtCore.pyqtSignal()
    def isUnique(self):
        socket = QtNetwork.QLocalSocket()
        socket.connectToServer('myApp')
        return not socket.state()

    def startListener(self):
        self.listener = QtNetwork.QLocalServer(self)
        self.listener.setSocketOptions(self.listener.WorldAccessOption)
        self.listener.newConnection.connect(self.anotherInstance)
        self.listener.listen('myApp')
        print('waiting for connections on "{}"'.format(self.listener.serverName()))


class Test(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        layout = QtWidgets.QVBoxLayout(self)
        self.label = QtWidgets.QLabel('Hello, I am new!')
        layout.addWidget(self.label)
        QtWidgets.QApplication.instance().anotherInstance.connect(self.anotherInstance)
        self.count = 0

    def anotherInstance(self):
        self.count += 1
        self.label.setText('That\'s {}, I am still here!'.format(self.count))
        self.showNormal()
        self.activateWindow()


if __name__ == '__main__':
    import sys
    app = UniqueApplication(sys.argv)
    if not app.isUnique():
        print('Application already running!')
    else:
        app.startListener()
        test = Test()
        test.show()
        sys.exit(app.exec())

推荐阅读