0

我希望使用字符串列表在 PyQt5 菜单栏中设置条目;列表可以更改。

从 Qt Designer ui 硬编码到 py 文件,我有:

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

不知道如何动态设置self.action,除了它应该在一个枚举循环中,但不知道如何从ui(现在是py)文件返回MainWindow。

在主程序中,我想...

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

messageScriptUi 文件的前几行是:

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")
4

1 回答 1

0

如果问题与动态创建操作有关,那么您使用setattr.

for name in strList:
    action = QtWidgets.QAction(MainWindow)
    setattr(self, 'action{}'.format(name), action)
    self.menuBoards.addAction(action)
于 2020-10-30T17:18:06.973 回答