【问题标题】:Dynamically add QAction to a QToolbar and create classmethods将 QAction 动态添加到 QToolbar 并创建类方法
【发布时间】:2015-02-24 11:41:12
【问题描述】:
  1. 我希望 QToolBar 像这样被实例化:

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

    tools.action_one()
    tools.action_two()...
    
  3. 这些方法应在“工具”之外可用,以便它们可以调用其他类的方法,例如:

    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...
    

【问题讨论】:

    标签: python-2.7 lambda closures pyqt4


    【解决方案1】:

    好的。这暂时有效:

    内部类方法:

    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,不过,请不要忘记学分...)

    【讨论】:

      猜你喜欢
      • 2014-05-20
      • 1970-01-01
      • 2017-06-25
      • 2013-01-16
      • 2017-07-09
      • 1970-01-01
      • 2012-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多