python - 使用参数 pyqt5 线程化一个类
问题描述
在下面的代码中,我尝试将需要 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__()
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_())
推荐阅读
- python - Python Selenium:使用 cookie 登录 facebook
- php - preg_match_all - 从搜索 php 中排除一个词
- mysql - 如果从数据框中删除重复的行
- python - 在 selenium webdriver python 中停止无限页面加载
- bootstrap-4 - Bootstap 5 导航项填充
- python - 从 Python 中的文件创建用户帐户的最佳方法?
- windows - Windows 上的子域
- python - 如何让熊猫从列表中的多个列表中获取值
- html - 如何仅使用 css 将图像移动到文本下方
- python - 递归寻路算法不断返回 None