pythonpython-3.xpyqtpyqt5qmenubar

Adding items to a menubar with a for loop - Pyqt5


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


Solution

  • 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)