0

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")
  • Unrelated note about your messageScriptUi: the logic there seems just wrong, and I believe you might have misunderstood how widgets should be created and how their parentship work. Why are you using `setupUi` to create the *parent* interface? Also, if you're creating a widget with a parent, that parent should be in its `__init__()` argument. Finally, python 3 doesn't normally need to specify arguments in `super()` as it was for python 2. – musicamante Oct 30 '20 at 17:21
  • Would you mind if I showed you my work (private email) so as not to trouble other readers? – oldHornPlayer Nov 02 '20 at 12:34
  • I'd prefer not to share my private address here on SO. If you have a specific question or doubt, add a comment or create a new post. – musicamante Nov 02 '20 at 12:52
  • Completely understandable. – oldHornPlayer Nov 02 '20 at 18:37

1 Answers1

0

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)
musicamante
  • 41,230
  • 6
  • 33
  • 58