PyQt proper use of emit() and pyqtSignal() PyQt proper use of emit() and pyqtSignal() python python

PyQt proper use of emit() and pyqtSignal()


You can define your own slot (any python callable) and connect that to the signal, then call the other slots from that one slot.

class Example(QWidget):    def __init__(self):        super().__init__()        self.initUI()    def printLabel(self, str):        print(str)    def logLabel(self, str):        '''log to a file'''        pass    @QtCore.pyqtSlot(int)    def on_sld_valueChanged(self, value):        self.lcd.display(value)        self.printLabel(value)        self.logLabel(value)    def initUI(self):        self.lcd = QLCDNumber(self)        self.sld = QSlider(Qt.Horizontal, self)        vbox = QVBoxLayout()        vbox.addWidget(self.lcd)        vbox.addWidget(self.sld)        self.setLayout(vbox)        self.sld.valueChanged.connect(self.on_sld_valueChanged)        self.setGeometry(300, 300, 250, 150)        self.setWindowTitle('Signal & slot')

Also, if you want to define your own signals, they have to be defined as class variables

class Example(QWidget):    my_signal = pyqtSignal(int)

The arguments to pyqtSignal define the types of objects that will be emit'd on that signal, so in this case, you could do

self.my_signal.emit(1)

emit can be reimplemented to send specific signal values to the slot function. It is also not yet clear why I would need to send different values from previously existing signal methods.

You generally shouldn't be emitting the built in signals. You should only need to emit signals that you define. When defining a signal, you can define different signatures with different types, and slots can choose which signature they want to connect to. For instance, you could do this

my_signal = pyqtSignal([int], [str])

This will define a signal with two different signatures, and a slot could connect to either one

@pyqtSlot(int)def on_my_signal_int(self, value):    assert isinstance(value, int)@pyqtSlot(str)def on_my_signal_str(self, value):    assert isinstance(value, str)

In practice, I rarely overload signal signatures. I would normally just create two separate signals with different signatures rather than overloading the same signal. But it exists and is supported in PyQt because Qt has signals that are overloaded this way (eg. QComboBox.currentIndexChanged)