pyqtpyqt5pyqt4signals-slots

PyQt4 to PyQt5 migration


For the last days i read a lot about new and old style of signals and slots. It seems now it's easier, but I stuck on one issue.

In my project old code generate dynamic signals based on name passed to it.

Example:

self.netlink.connect(self.netlink,SIGNAL(self.modelName + "_gotCommand"),self.processCommand)

and here is emit

self.emit(SIGNAL(model + "_gotCommand"), cmd, data)

data can be diffrenet type (list , tuple, string , etc) again based on model

So how can I move this code into Qt5 as we need describe each signal with pyqtSignal definition.


Solution

  • It is not possible to dynamically emit arbitrary signals using the new-style syntax. All signals must be pre-defined in the class.

    Your example does not make it clear why you need to use a different signal-name for each model, since you are always connecting to the same slot. It would seem to make more sense to have each model emit the same signal, perhaps also sending the model name, if necessary:

    class SomeModel(QObject):
        gotCommand = pyqtSignal(str, str, object)
    
        def doSomething(self):
            ...
            self.gotCommand.emit(model, cmd, data)
    
    ...
    
    self.netlink.gotCommand.connect(self.processCommand)
    

    But if you still need to connect/emit signals by key, you can use getattr:

    getattr(self.netlink, self.modelName + "_gotCommand")).connect(self.processCommand)
    

    and:

    getattr(self, model + "_gotCommand").emit(cmd, data)