将 QAction 动态添加到 QToolbar 并创建类方法

Dynamically add QAction to a QToolbar and create classmethods

  1. 我希望 QToolBar 像这样被实例化:

    tools = customTools(actions=['action_one', 'action_two', 'action_three'])
    
  2. 和编程添加的类方法,所以有(对应每个动作发出的信号):

    tools.action_one()
    tools.action_two()...
    
  3. 这些方法应在 "tools" 之外可用,因此它们可以调用其他 类 的方法,例如:

    class customTools(QtGui.QToolBar):
        """represents a custom QToolBar"""
        ...
        def action_one(self):
            some_other_classes.function()
    
  4. 现在,我卡在这里:

    class customTools(QtGui.QToolBar):
        def __init__(self, actions=[]):
            QtGui.QToolBar.__init__(self, parent=None)
    
            #actions to toolbar QAction
            for name in actions:
                action = QtGui.QAction(name, self)
                self.addAction(action)
                action.triggered[()].connect(
                    lambda name=name: self.tool_name(name))
    
        def tool_name(self, name):
            # stuck here...
    

好的。这现在有效:

内部类方法:

def tool_name(self, f):
    self.function = getattr(self, f)
    self.function()

实例化:

def main():
    names = ['action_one', 'action_two']
    tools = customTools([name for name in names])

定义函数:

def action_one(self):
    return some_other_classes.function()

添加为类方法:

setattr(tools, action_one.__name__, MethodType(action_one, tools, type(tools)))

(在此处找到:http://dietbuddha.blogspot.com/2012/12/python-metaprogramming-dynamically.html,不过不要忘记学分...)