怎么构建一个QApplication实例,项目启动时先让他先运行起来,但是不显示任何窗口,然后能通过websocket发的请求参数调用,可以多次重复显示不同窗口?-灵析社区

喵酱魔法师

class MyApp(QApplication): instance = None @staticmethod def getInstance(): if MyApp.instance is None: MyApp.instance = MyApp(sys.argv) return MyApp.instance class WindowManager(QObject): def __init__(self): super().__init__() self.currentWindow = None @Slot(str) def handleRequest(self, requestType, app, **kwargs): if requestType == "idcard": self.currentWindow = IdCardView() elif requestType == "keypad": self.currentWindow = KeyPadView(kwargs.get("flag")) elif requestType == "financeIcCard": self.currentWindow = FinanceIcCardView() elif requestType == "mockMagnetIC": self.currentWindow = MagneticView() self.currentWindow.ui.show() app.exec() return self.currentWindow.getData() def run_app(windowType, **kwargs): app = MyApp.getInstance() windowManager = WindowManager() return windowManager.handleRequest(windowType, app, flag=kwargs.get("flag")) 想通过run()方法传入不同的参数,根据参数调用对应的窗口且返回数据,但是这里会阻塞,请问这个可以怎么改造

阅读量:13

点赞量:0

问AI
import sys from PyQt5.QtWidgets import QApplication, QWidget from PyQt5.QtCore import QObject, pyqtSlot import socket class MyApp(QApplication): instance = None @staticmethod def getInstance(): if MyApp.instance is None: MyApp.instance = MyApp(sys.argv) return MyApp.instance class WindowManager(QObject): def __init__(self): super().__init__() self.currentWindow = None @pyqtSlot(str) def handleRequest(self, requestType): if self.currentWindow: # 如果已经有窗口打开,先关闭它 self.currentWindow.close() # 根据requestType创建对应的窗口 if requestType == "idcard": self.currentWindow = QWidget() # Just an example, replace with your actual view self.currentWindow.show() def run_app(): app = MyApp.getInstance() windowManager = WindowManager() server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(('localhost', 12345)) server_socket.listen(1) print("Listening on port 12345...") while True: client_socket, address = server_socket.accept() requestType = client_socket.recv(1024).decode() client_socket.close() # 在主线程中调用handleRequest方法 QApplication.instance().thread().exec_(lambda: windowManager.handleRequest(requestType)) if __name__ == "__main__": run_app()