Yuushi
Yuushi

Reputation: 26080

Connecting subclass signal to superclass slot

Given a superclass that defines a slot:

class Foo(object):

    @pyqtSlot()
    def my_slot(self):
        print('Called my_slot')

Is it then possible to hook up a signal from a subclass to this?

class Bar(QWidget, Foo):

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        Foo.__init__(self)
        self.combo = QComboBox()
        self.combo.currentIndexChanged[str].connect(
            self.my_slot)

This fails as it does not seem to look in the base classes for my_slot. Is this possible and what is the syntax to achieve it?

Upvotes: 2

Views: 1192

Answers (2)

ekhumoro
ekhumoro

Reputation: 120768

In PyQt4, you cannot use the pyqtSignal and pyqtSlot decorators in a subclass that doesn't inherit from QObject. It's also not possible to inherit from more than one class that inherits from QObject - which means that, in general, there is no way to inherit custom signals and slots in subclasses. Most of these restrictions have been lifted in recent versions of PyQt5, and I don't think PySide has ever had them - but they are a permanent a part of PyQt4.

So the simplest way to solve your issue, is to simply remove the pyqtSlot decorator from the my_slot method. It is generally quite rare that you will need to use the pyqtSlot decorator. The most common reasons for using it are to provide multiple overloads for connecting to signals with several different signatures, and sometimes to ensure thread safety when connecting signals and slots between threads.

See New-style Signal and Slot Support in the PyQt4 Docs for more details.

Upvotes: 1

Yuushi
Yuushi

Reputation: 26080

I figured out a way of doing this - I'm not sure if it is the best way.

You need to override the slot you want to call in the subclass and forward it to the superclass:

class Bar(QWidget, Foo):

    def __init__(self, parent=None):
        # As before

    @pyqtSlot()
    def my_slot(self):
        super(Bar, self).my_slot()

Upvotes: 2

Related Questions