python - 如何从线程内访问外部属性

标签 python multithreading pyqt pyqt5 python-multithreading

我用 PyQt5 Designer 设计了一个 GUI。

我希望 tryingMethod 始终检查来自服务器的传入消息,因此我创建了一个线程,以便 GUI 和 run 方法可以同时运行,这很有效。

问题是,当我尝试从 Ui_Form 访问变量“Button”时,它会抛出以下错误:AttributeError:“Ui_Form”对象没有属性“Button”。

我曾尝试将 self 作为参数传递给 waitingMethod 线程,但它给了我“意外类型:(() -> None, Ui_Form) 警告”

我尝试创建几个不同的类,但无法解决该问题。任何帮助表示赞赏! :)

class Ui_Form(object):
    def __init__(self):
        t = threading.Thread(target=self.tryingMethod)
        t.start()




    def tryingMethod(self):
        self.Button.setText("TESTING")  ##This doesn't work.

        while True:
            message = self.clientSocket.receive()



    def setupUi(self, Form):
        //Code has been shortened
        self.Button.setFont(font)
        self.Button.setCursor(QtGui.QCursor(QtCore.Qt.ForbiddenCursor))
        self.Button.setObjectName("Button")



if __name__ == "__main__":
     app = QtWidgets.QApplication(sys.argv)
     Form = QtWidgets.QWidget()
     ui = Ui_Form()
     ui.setupUi(Form)
     Form.show()
     sys.exit(app.exec_())

最佳答案

Qt 不允许直接从另一个线程更新 GUI,一个可能的解决方案是使用信号,但为此我们需要一个继承 QObject 的类,但另一方面不建议这样做修改 Qt Designer 生成的类,该类仅用于填充小部件因此您可以利用创建一个继承自小部件的类,并且由于它是一个小部件也继承自 QObject ,在该类中我们将创建一个信号,并将该信号连接到按钮的 setText() 方法。

class Ui_Form(object):
    def setupUi(self, Form):
        # Code has been shortened
        self.Button.setFont(font)
        self.Button.setCursor(QtGui.QCursor(QtCore.Qt.ForbiddenCursor))
        self.Button.setObjectName("Button")

class Form(QtWidgets.QWidget, Ui_Form):
    someSignal = QtCore.pyqtSignal(str)
    def __init__(self, *args, **kwargs):
        QtWidgets.QWidget.__init__(self, *args, **kwargs)
        self.setupUi(self)
        t = threading.Thread(target=self.tryingMethod)
        self.someSignal.connect(self.Button.setText)
        t.start()

    def tryingMethod(self):
        self.someSignal.emit("TESTING")  ##This doesn't work.
        while True:
            message = self.clientSocket.receive()


if __name__ == "__main__":
     app = QtWidgets.QApplication(sys.argv)
     w = Form()
     w.show()
     sys.exit(app.exec_())

关于python - 如何从线程内访问外部属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49850047/

相关文章:

Python - 还有其他方法可以在列表理解中应用函数和过滤器吗?

python - 请求.exceptions.SSLError : Errno 185090050

python - 在两个 QWizardPage 之间弹出一个包含 QProgressBar 的小部件

python - 字典的平均值

python - 错误: 'str' object has no attribute 'shape' while trying to covert datetime in a dataframe

java - Android - 使用 Callable 进行联网

multithreading - 将子例程引用传递给 Perl 线程

Java从另一个线程更新jtable行

python - PyQT 读取文本文件

python - 用于ubuntu的pyqt gui应用程序打包