0

I have a list of name and from that list, I would like to populate a menubar of my QMainWindow. Below an attempt of code:

list_name = ['Miller', 'Johnson', 'Robert']
self.menuName = self.menuBar().addMenu('Name')
for i in range(0,3):
    list_name[i]+'_action' = QtWidgets.QAction(list_name[i], self)
    self.menuName.addAction(list_name[i])

Here the error:

enter image description here

Thank you

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
H. Dave
  • 549
  • 3
  • 9
  • 26

1 Answers1

1

You can not assign a variable to a string, you must do the opposite, besides it is not necessary that the variable has a different name.

To make it more readable, you can also iterate through the list instead of iterating over numbers.

list_name = ['Miller', 'Johnson', 'Robert']
self.menuName = self.menuBar().addMenu('Name')
for name in list_name:
    action = QtWidgets.QAction(name, self)
    self.menuName.addAction(action)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Awesome! Just a quick question. How can I connect the menubar items to the same def? Should have to include this kind of code into the loop: `self.name_action.triggered.connect(self.def_name)` ? Thanks – H. Dave Oct 15 '17 at 18:56
  • 1
    If you want to connect all the QAction to the same function you only have to use: `action.triggered.connect(self.def_name)`. If you want to filter in the function you only have to use `self.sender()`. Please do not forget to mark my answer as correct. – eyllanesc Oct 15 '17 at 19:01
  • One more thing... How can I pass the name of the item selected as a variable? I did this `action.triggered.connect(lambda item=name: self.def_name(item))` but that returns `False` when I print the variable. Thanks – H. Dave Oct 15 '17 at 21:28
  • 1
    What are the def_name input parameters? `action.triggered.connect(lambda checked, item=name: self.def_name(item))` – eyllanesc Oct 15 '17 at 22:55
  • Thank you for your help, by adding the `checked` my code works – H. Dave Oct 15 '17 at 23:11