Python 使用参数pyqt5线程化类
在下面的代码中,我尝试对需要x作为参数的计算类执行线程,当没有x时,该线程可以完美地工作。但是,一旦我提出了一个论点,事情就错过了,我能知道为什么吗Python 使用参数pyqt5线程化类,python,multithreading,pyqt5,qthread,Python,Multithreading,Pyqt5,Qthread,在下面的代码中,我尝试对需要x作为参数的计算类执行线程,当没有x时,该线程可以完美地工作。但是,一旦我提出了一个论点,事情就错过了,我能知道为什么吗 from PyQt5 import QtCore, QtGui, QtWidgets from mainwindow2 import Ui_Form import time class Calculation(QtCore.QThread): def __init__(self,x): super().__init__()
from PyQt5 import QtCore, QtGui, QtWidgets
from mainwindow2 import Ui_Form
import time
class Calculation(QtCore.QThread):
def __init__(self,x):
super().__init__()
self.x = x
def run(self):
for i in range(10):
if i!=5:
time.sleep(1)
print(i+self.x)
class MainWindow(QtWidgets.QMainWindow, Ui_Form):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.pressed.connect(self.threadingc)
def threadingc(self):
# create the thread with the main window as a parent, this is possible
# since QMainWindow also inherits from QObject, and this also ensures
# that python will not delete it if you want to start another thread
self.pushButton.setEnabled(False)
thread = Calculation(5)
thread.start()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
主窗口2
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(400, 300)
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(150, 110, 93, 28))
self.pushButton.setObjectName("pushButton")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "PushButton"))
您需要向线程提供父变量
from PyQt5 import QtCore, QtGui, QtWidgets
import time
class Calculation(QtCore.QThread):
def __init__(self, parent, x):
# I have added the parent variable.
super().__init__(parent)
self.x = x
def run(self):
for i in range(10):
if i != 5:
time.sleep(1)
print(i + self.x)
class MainWindow(QtWidgets.QMainWindow, Ui_Form):
...
def threadingc(self):
# You need to provide a reference to the gui or make the thread a class variable.
thread = Calculation(self, 5)
thread.start()
# If you don't provide a parent or make the thread a class variable the function scope will
# end here and the thread variable will be terminated.
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
分享你的用户界面表单too@ShoaibMirzaei doneI我不确定你想用你的代码做什么。但是您的代码没有对
self.error
的定义,并且工作正常。您必须将self.run()
添加到类计算的@ShoaibMirzaei的\uuuu init\uuuu
函数中。对我来说,它根本不起作用。我运行代码,然后将其阻止。请仔细阅读前面的内容并尝试理解其机制,不要在不知道自己在做什么的情况下修改内容。例如,正如这里所解释的,如果您没有设置对线程的持久引用,那么parent(self
)参数非常重要(您还复制了关于该线程的注释,这使我认为您实际上没有阅读或理解它)。