인수 pyqt5 [duplicate]로 클래스 스레딩

Nov 13 2020

다음 코드에서 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_())

mainwindow2

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"))

답변

1 maxwiklund Nov 13 2020 at 01:07

스레드에 부모 변수를 제공해야합니다.

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_())