开发者

PyQT - creating a large list of actions

I'm working on some code where I need to create a list of QActions corresponding to the COM ports on the system, which will be added to the menu bar depending upon which COM ports are available. It looks sort of like this:

    self.actionCOM1 = QtGui.QAction(QtGui.QIcon(''), 'COM1', self)
    self.actionCOM1.setCheckable(True)
    self.COMPorts.append(self.actionCOM1)e here

It would make my life easier if there were a way to do this so I didn't have to repeat this block of code over and 开发者_开发技巧over, is there some way to just append a loop index number to the end of "self.actionCOM"?


Do you mean something like this?

num = 10
for i in range(num):
    setattr(self, "actionCOM%d" % i, QtGui.QAction(QtGui.QIcon(''), "COM%d" % i, self))
    action = getattr(self, "actionCOM%d" % i)
    action.setCheckable(True)
    self.COMPorts.append(action)


If it's an option for you, I'd consider using a dictionary for this purpose rather than dynamically created attrs on the instance.

self.actionCOM = {}
for com_port in list_of_com_ports:
    self.actionCOM[com_port] = QtGui.QAction(QtGui.QIcon(''), 'COM%d'%com_port, self)
    self.actionCOM[com_port].setCheckable(True)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜