Search code examples
pythonpluginspyqtsignals-slotsqaction

How to reimplement triggered() signal in pyqt for a QAction?


I'm using Python with PyQt, for my interface, and Yapsi, for add plugins. Yapsy found all my plugins and add all to a menu in my mainWindow. Each plugin, is activated with triggered signal. This signal for a QAction don't have params and I need know what plugin was emit the signal.

This is the relevant code:

pluginMenu = self.menuBar().addMenu("P&lugins")

# Create plugin manager
self.manager = PluginManager(categories_filter={ "Formatters": Formatter})
self.manager.setPluginPlaces(["plugins"])

# Load plugins
self.manager.locatePlugins()
self.manager.loadPlugins()

# A do-nothing formatter by default
self.formatters = {}

for plugin in self.manager.getPluginsOfCategory("Formatters"):

# plugin.plugin_object is an instance of the plugin
print(plugin.plugin_object.name)
# The method to create action associated each input to default triggered() signal
newAction = self.createAction(plugin.plugin_object.name, slot=self.updatePreview())


self.addActions(pluginMenu, (newAction, None))
self.formatters[plugin.plugin_object.name] = (plugin.plugin_object, newAction)

def updatePreview(self):
    # Here I need know what plugin emit the signal    
    #===================================================================

I thought to conect the signal with other signal with some params but I don't know how to do it.


Solution

  • I don't know what's Yapsi, but there is QObject.sender method:

    QObject QObject.sender (self)

    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.

    The pointer returned by this function becomes invalid if the sender is destroyed, or if the slot is disconnected from the sender's signal.

    Warning: This function violates the object-oriented principle of modularity. However, getting access to the sender might be useful when many signals are connected to a single slot.

    Warning: As mentioned above, the return value of this function is not valid when the slot is called via a Qt.DirectConnection from a thread different from this object's thread. Do not use this function in this type of scenario.

    Some more tips here: http://blog.odnous.net/2011/06/frequently-overlooked-and-practical.html