user1579230
user1579230

Reputation: 203

connecting signal with method of self in PyQt4

I am having difficulty connecting a signal with a method in PyQt4. I can connect a bound signal of object A with a method of object B, but I can't connect a bound signal of object A with a method of self (object where the connections are made.)
What am I doing wrong? See below:

from PyQt4.QtGui import *
from PyQt4.QtCore import *


class FooA(QObject):
    trigger=pyqtSignal(str)

    def receive_trigger(self,a):
        print'triggered in FooA, string',a

class MainObj(QObject):
    def __init__(self):
        self.a1=FooA()
        self.a2=FooA()
        #I can connect signals and methods of separate objects:
        self.a1.trigger.connect(self.a2.receive_trigger)
        self.a1.trigger.emit('hi')
        #... but I can't connect a signal with a method of self
        self.a1.trigger.connect(self.receive_trigger)
        self.a1.trigger.emit('hi')
    def receive_trigger(self,a):
        print 'triggered in MainObj'

executes as: MainObj()

triggered in FooA, string hi triggered in FooA, string hi

I expected to see an additional line, > triggered in MainObj

Thanks in advance. Bill

Upvotes: 1

Views: 865

Answers (1)

D K
D K

Reputation: 5760

As you already seem to know, signals must belong to QObjects, but this problem is occurring because you are not calling the constructor of QObject. FooA does not override the constructor, therefore the default constructor is called and the signals work as expected. In MainObj however, you do not call the superclass' (QObject) constructor, so signals will not work. To fix, either put:

QObject.__init__(self)

or

super(QObject, self).__init__()

(based on your conventions) at the top of MainObjs contructor, and the signals will then work as expected.

Upvotes: 2

Related Questions