错误1
Process finished with exit code -1073741819 (0xC0000005)
QMessageBox
需要在主线程中使用,不能在子线程中使用。
import sys
import time
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox
from PyQt5.QtCore import QThread, pyqtSignal
class MyTask(QThread):
def run(self):
time.sleep(5)
QMessageBox.warning(None, 'error', 'error msg')
class Win(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.resize(600, 400)
self.t = None
self.test()
def test(self):
self.t = MyTask()
self.t.start()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Win()
win.show()
app.exec_()
错误2
Process finished with exit code -1073740791 (0xC0000409)
变量t
需要改为类级变量,self.t
import sys
import time
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox
from PyQt5.QtCore import QThread, pyqtSignal
class MyTask(QThread):
sig = pyqtSignal(object)
def run(self):
time.sleep(5)
self.sig.emit('111111111')
class Win(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.resize(600, 400)
t = MyTask()
t.sig.connect(self.out)
t.start()
def out(self, obj):
QMessageBox.warning(None, 'error', obj)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Win()
win.show()
app.exec_()
正确
import sys
import time
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox
from PyQt5.QtCore import QThread, pyqtSignal
class MyTask(QThread):
sig = pyqtSignal(object)
def run(self):
time.sleep(5)
self.sig.emit('111111111')
class Win(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.resize(600, 400)
self.t = MyTask()
self.t.sig.connect(self.out)
self.t.start()
def out(self, obj):
QMessageBox.warning(None, 'error', obj)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Win()
win.show()
app.exec_()
注意:窗口显示必须搞到主线程中去管理不能在子线程中去调用显示,否则就会导致页面卡死。