convert PyQt4 string styled signal to PyQt5 Signal

2020-05-01 06:12发布

问题:

I usually write a small function to create QActions. But PyQt5 doesn't support function SIGNAL() anymore. I don't know how to rewrite this function beautifully.

def createAction(self, text, slot=None, signal='triggered()'):
    action = QAction(text, self)
    if slot is not None:
        self.connect(action, SIGNAL(signal), slot)
    return action

回答1:

I think you may be over-thinking this. New-style signals are instance attributes, so you can just use getattr:

def createAction(self, text, slot=None, signal='triggered'):
    action = QAction(text, self)
    if slot is not None:
        getattr(action, signal).connect(slot)
    return action


回答2:

The problem here is about use a string (by name) to reference a signal.

There are three ways to connect signals under PyQt5. see connecting signals by kwargs So I come out with this solution.

def createAction(self, text, slot=None, signal='triggered'):
    action = QAction(text, self)
    signal_dict = {'triggered':action.triggered, 'changed':action.changed,
                    'toggled':action.toggled, 'hovered':action.hovered }
    if slot is not None:
        # self.connect(action, SIGNAL(signal), slot)
        signal_dict[signal].connect(slot)
    return action


标签: pyqt pyqt4 pyqt5