Python: add entries to PyQt5 menu bar list

330 views Asked by At

I wish to set the entries in an PyQt5 menu bar with a list of strings; the list can change.

Hard-coded from Qt Designer ui to py file, I have:

strList = ["1", "2", "3", "4" ]

self.action1 = QtWidgets.QAction(MainWindow)
self.action1.setObjectName("action1")
self.action2 = QtWidgets.QAction(MainWindow)
self.action2.setObjectName("action2")
self.action3 = QtWidgets.QAction(MainWindow)
self.action3.setObjectName("action3")
self.action4 = QtWidgets.QAction(MainWindow)
self.action4.setObjectName("action4")
self.menuBoards.addAction(self.action1)
self.menuBoards.addAction(self.action2)
self.menuBoards.addAction(self.action3)
self.menuBoards.addAction(self.action4)
self.menubar.addAction(self.menuBoards.menuAction())

Not sure how to dynamically set the self.action, except that it should be in an enumerate loop like, but not sure how to return MainWindow from ui (now py) file.

In the main program, I thought...

import messageScriptUi
#lines later
for ix, name in enumerate(strList):
    setattr(self, name, QtWidgets.QAction(MainWindow) )
    #-------------help here?-------------------
    self.menuBoards.addAction(self.action1)
    #------------------------------------------
self.menubar.addAction(self.menuBoards.menuAction()) 

The top few lines of the messageScriptUi file are:

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QWidget, QMainWindow

class Ui_Form(QWidget):
# Start code to copy
def __init__(self, parent):
    super(self.__class__, self).__init__()
    self.parent = parent
    self.setupUi(parent)
    
def setCentralWidget(self, something):
    pass

def setupUi(self, MainWindow):
    MainWindow.setObjectName("MainWindow")
1

There are 1 answers

0
musicamante On

If the issue is about dynamically creating actions, you were half way by using setattr.

for name in strList:
    action = QtWidgets.QAction(MainWindow)
    setattr(self, 'action{}'.format(name), action)
    self.menuBoards.addAction(action)