简体   繁体   English

pyqt5 qthread未知原因崩溃,如何正确使用?

[英]pyqt5 qthread crash for unkown reason,how to use it correctly?

I am new to pyqt5 and I find a wield problem that I can't explain 我是pyqt5的新手,我发现了一个我无法解释的问题

First of all,I figure I should use QObject rather than Qthread directly when I try to solve this problem in my own way,but I just curious why this happened 首先,我想尝试以自己的方式解决此问题时,应该直接使用QObject而不是Qthread,但是我很好奇为什么会这样

If I use Qthread(self),and the program works fine, but if I use Qthread(),don't pass self to Qthread parent, the program crashes. 如果我使用Qthread(self),并且程序运行正常,但是如果我使用Qthread(),则不要将self传递给Qthread父级,则程序将崩溃。 This is not weild, what is weild is that I use Qthread(), and add a line time.sleep(0.1),the code works fine too, I couldn't figure out why, can someone explain it. 这不是奇怪的,而是我使用Qthread()并添加一行time.sleep(0.1),代码也可以正常工作,我不知道为什么,有人可以解释一下。

I use Python a lot, but new to pyqt5, and it code is in C++, I can't read the source code to find why. 我经常使用Python,但对pyqt5还是陌生的,它的代码是C ++,我无法阅读源代码来找到原因。 here is my code: 这是我的代码:

from PyQt5.QtWidgets import QWidget, QPushButton, QApplication, QGridLayout
from PyQt5.QtCore import QThread
import sys
import time
import threading


class MyThread(QThread):
    def run(self):
        print('working', threading.current_thread())


class MyHelper(QWidget):

    def __init__(self):
        super(MyHelper, self).__init__()
        self.init_ui()

    def init_ui(self):
        self.submit_button = QPushButton('submit')
        self.submit_button.clicked.connect(self.click_op)
        self.my_grid = QGridLayout()
        self.my_grid.addWidget(self.submit_button, 1, 1)
        self.setLayout(self.my_grid)
        self.setGeometry(300, 300, 350, 300)
        self.show()

    def click_op(self):
        '''
            my_sender = MyThread()  crash
            my_sender = MyThread(self) OK
            my_sender = MyThread() + time.sleep(0.1) OK, most weild one
        '''
        my_sender = MyThread()
        # my_sender = MyThread(self)
        my_sender.start()
        time.sleep(0.1)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    email_helper = MyHelper()
    exit(app.exec_())

Local variables are automatically destroyed at the end of the function, declaring my_sender as a class variable 局部变量在函数末尾自动销毁,将my_sender声明为类变量

self.my_sender = MyThread()
self.my_sender.start()

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

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