I. A. Gerogiannis I. A. Gerogiannis - 7 days ago 6
Python Question

How create QActions and their signals according to file

I am using python3 and PyQt4. I want to create a menu with actions, the number of which differs according to an array. I want each of them to save the corresponding information, saved in the array, to a variable. Creating variable number of events seems impossible. So how can i create an event which does different work, according to the action it was activated by?
That' s my code:

def buildLoadSettings(self):
self.settings = array
for i in range(len(self.settings)):
exec("self.settings" + str(i) + " = QtGui.QAction('" + self.settings[i][0] + "', self)")
exec("self.loadMenu.addAction(self.settings" + str(i) + ")")


I want to connect each of the actions with an event and finally save the "self.settings[i][1]" to a variable "settings".
Sorry for my novice question.

Answer

It's not completely clear what you're trying to achieve, but there are several APIs that should help. There is certainly no need to use ugly exec calls like you are at present.

Here are a few ideas:

  1. Use QAction.setData() to associate some data with each action:

        for item in self.settings:
            action = QtWidgets.QAction(item[0], self)
            action.setData(item[1])
            self.loadMenu.addAction(action)
    
  2. Use QMenu.actions() to access the actions, rather than creating attributes:

        action = self.loadMenu.actions()[2]
        print((action.text(), action.data()))
    
  3. Connect a slot to QMenu.triggered() to handle all of its actions in one place:

        self.loadMenu.triggered.connect(self.handleLoadMenu)
    
    def handleLoadMenu(self, action):
        # "action" is the action that was clicked
        text = action.text()
        data = action.data()
        print('Action Clicked: ("%s", %s)' % (text, data))
    

PS:

If you want to get/set attributes dynamically, use getattr and setattr:

    # self.settings2 = action
    setattr(self, "settings%s" % 2, action)
    # action = self.settings2
    action = getattr(self, "settings%s" % 2)