简体   繁体   English

在子multiprocessing.Process(Python3)中打开PyQt5窗口

[英]Open PyQt5 window in child multiprocessing.Process (Python3)

I'm trying to open a second window in a new process to not freeze the main window with PyQt5. 我正在尝试在新过程中打开第二个窗口,以不冻结PyQt5的主窗口。 For this reason, I define a new class that inherits from multiprocessing.Process and shows the window. 因此,我定义了一个新类,该类继承自multiprocessing.Process并显示了窗口。 This is the main code: 这是主要代码:

class GuiMain(QMainWindow):
    ...
    # Main window with several functions. When a button is clicked, executes 
    # self.button_pressed()

    def button_pressed(self):
        proc1 = OpenWindowProcess()
        proc1.start()


class OpenWindowProcess(mp.Process)

    def __init__(self):
        mp.Process.__init__(self)
        print(self.pid)

    def run(self):
        print("Opening window...")
        window = QtGui.QWindow()
        window.show()
        time.sleep(10)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    application = GuiMain()
    sys.exit(app.exec_())

The process is created and gets a PID. 该过程已创建并获得PID。 When run() function is called, the message "Opening window.." is displayed, but nothing else happens. 调用run()函数时,显示消息“正在打开窗口。。”,但没有其他任何反应。 No window, no error... I can't figure out whats happening. 没有窗口,没有错误...我不知道发生了什么。 Thank you in advance! 先感谢您!

I've come to a solution. 我已经解决了。 You have to create a new QtApplication and attach to it a new QMainWindow instance. 您必须创建一个新的QtApplication并附加一个新的QMainWindow实例。 This code works fine: 这段代码可以正常工作:

class GuiMain(QMainWindow):
    ...
    # Main window with several functions. When a button is clicked, executes 
    # self.button_pressed()

    def button_pressed(self):
        proc1 = OpenWindowProcess()
        proc1.start()


class OpenWindowProcess(mp.Process)

    def __init__(self):
        mp.Process.__init__(self)
        print("Process PID: " + self.pid)

    def run(self):
        print("Opening window...")
        app = QApplication(sys.argv)
        window = QMainWindow()
        window.show()
        sys.exit(app.exec_())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    application = GuiMain()
    sys.exit(app.exec_())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM