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()