gustavgans
gustavgans

Reputation: 5191

how to get key sequence after sending a SIGNAL

I bind 2 keys to call 2 methods of my class. Is it possible to call the some method and knowing which key was pressed?

def initGui(self):
    self.keyAction = QAction("Test Plugin", self.iface.mainWindow())
    self.iface.registerMainWindowAction(self.keyAction, self.toggle_key_1)
    self.iface.addPluginToMenu("&Test plugins", self.keyAction)
    QObject.connect(self.keyAction, SIGNAL("triggered()"), self.toogle_layer_1)

    self.keyAction = QAction("Test Plugin", self.iface.mainWindow())
    self.iface.registerMainWindowAction(self.keyAction, self.toggle_key_2)
    self.iface.addPluginToMenu("&Test plugins", self.keyAction)
    QObject.connect(self.keyAction, SIGNAL("triggered()"), self.toogle_layer_2)

Upvotes: 0

Views: 127

Answers (1)

vahancho
vahancho

Reputation: 21248

Yes, you can know which object has triggered the signal from your slot (function) with using QObject::sender() function. As Qt docs say:

Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. The pointer is valid only during the execution of the slot that calls this function from this object's thread context.

Update:

For example, in your slot you can write:

def toogle_layer(self):
    action = QtCore.QObject.sender()

    if action == self.action1:
        # do something
    elif action == self.action2:
        # do something else

Upvotes: 2

Related Questions