python - 如果应用程序已经打开,则聚焦打开的应用程序窗口,同时再次单击应用程序图标
问题描述
我对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)
上面的代码防止了应用程序的多次打开。如果我们打开多个应用程序,它会使用“应用程序已在运行”的日志消息来阻止。如果应用程序已经处于打开状态,我需要在单击应用程序图标时聚焦或激活已打开的应用程序窗口。请指导我。谢谢
解决方案
最简单的方法是使用QLocalServer和QLocalSocket,它允许创建本地连接并在应用程序之间进行通信,但在这种情况下,检查服务器是否已经存在或在尝试新连接时收到通知就足够了:
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())
推荐阅读
- r - 我不能在 R 的其他函数中使用函数吗?
- python - 使用 RequestHandler.set_secure_cookie() 的龙卷风不允许添加 samesite 属性
- c - 为什么在linux系统调用实现中需要“asmlinkage”?
- javascript - 文档 querySelectorAll 以查找元素的部分属性名称?
- python - 在numpy中重新排序矩阵
- go - 多个生产者,单个消费者:所有 goroutine 都处于休眠状态 - 死锁
- python-3.x - Tensorflow 2.0 中的时间序列预测 - 如何使用最后一个验证数据集进行预测?
- python - 如果有的话(s in line for s in list):打印行...不工作
- excel - 为什么 VLookup 不一致?
- ansible - Ansible 模板和 jinja {%block%}