I am new to pyqt5 and I find a wield problem that I can't explain
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
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. 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.
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. 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
self.my_sender = MyThread()
self.my_sender.start()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.