简体   繁体   English

如何通过PySide上的另一个线程从QMainWindow类捕获Signal?

[英]How to catch a Signal from QMainWindow class by another thread on PySide?

I have a MainWindow class which have a Gui application running on it and i want that every time i click on a button from my application a signal is emitted and caught by another thread. 我有一个MainWindow类,该类上运行有Gui应用程序,我希望每次我从应用程序中单击按钮时,都会发出信号并被另一个线程捕获。 There is my example code (sorry for not posting my real code but it is real big now): 有我的示例代码(很抱歉,我没有发布我的真实代码,但现在确实很大):

from PySide.QtGui import *
from PySide.QtCore import *
import sys
import mainGui    #Gui file

class MainWindow(QMainWindow, mainGui.Ui_MainWindow):

mySignal = Signal()


    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.newThread = workThread()
        self.newThread.start()

        #myButton is part of Gui application
        self.myButton.clicked.connect(self.myfunction)

    def myfunction(self):
        self.mySignal.emit()

    (...) #Other functions and methods

class workThread(QThread):
     def __init__(self, parent=None):
         super(workThread, self).__init__(parent)

         #The problem:
         MainWindow.mySignal.connect(self.printMessage)

     def run(self):
          (...)

     def printMessage(self):
         print("Signal Recived")
         (...)


def main():
    app = QApplication(sys.argv)
    form = MainWindow()
    form.show()
    app.exec_()

if __name__=="__main__":
    main()

... and i get the following error: MainWindow.mySignal.connect(self.printMessage) AttributeError: 'PySide.QtCore.Signal' object has no attribute 'connect' ...并且出现以下错误:MainWindow.mySignal.connect(self.printMessage)AttributeError:'PySide.QtCore.Signal'对象没有属性'connect'

There is any ideia how can i solve this? 有什么想法我该如何解决? Thanks in advance! 提前致谢!

Signals are just like methods - they must be bound to instances. 信号就像方法一样-它们必须绑定到实例。 They won't work correctly if you try to access them directly via the class. 如果您尝试直接通过类访问它们,它们将无法正常工作。

One way to fix the example is to pass the instance of MainWindow in as the parent of the thread, like so: 解决该示例的一种方法是将MainWindow的实例作为线程的父级传入,如下所示:

    self.newThread = workThread(self)
    ...

    parent.mySignal.connect(self.printMessage)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM