Search code examples
pyqtqt4signals-slots

How to connect the Signal an the Slot in PyQt


My compile environment is PyQt4,Qt4,Python2.In my code,there is a Signal:

class ReadThread(QtCore.QThread):
    #always read UART RX pin
    def __init__(self,parent=None):
        QtCore.QThread.__init__(self,parent)
        self.trigger=QtCore.pyqtSignal()#creat a signal

    def run(self):
        #thread stop when the "run" function is over
        for i in range (25536):
            pass
        self.trigger.emit()

And there is a Slot() in Class ChatDialog.

class ChatDialog(QtGui.QDialog):
    #dialog contain two widget-"recived"and"send"
    def __init__(self,parent=None):
        QtGui.QDialog.__init__(self,parent)
        self.ui=Ui_Dialog()
        self.ui.setupUi(self)

    @QtCore.pyqtSlot()
    def print_slot():
        print "reciece str"

I write the __main__like this:

if __name__=='__main__':
        app = QtGui.QApplication(sys.argv)
        myqq=ChatDialog()
        myqq.show()
        read=ReadThread()
        read.trigger.connect(myqq.print_slot,QueuedConnection)
        read.start()
        sys.exit(app.exec_())

But my "read.trigger.connect(myqq.print_slot,QueuedConnection)" is wrong.How can I connect the Signal and the Slot?Thanks


Solution

  • Signals have to be defined as a class attributes. You cannot create signals on instances.

    class ReadThread(QtCore.QThread):
    
        trigger = QtCore.pyqtSignal()
    
        def __init__(self,parent=None):
            QtCore.QThread.__init__(self,parent)