我想要将QToolBar实例化为:
tools = customTools(actions=['action_one', 'action_two', 'action_three'])
以及以编程方式添加的类方法,因此存在(对应于每个动作发出的信号):
tools.action_one()
tools.action_two()...
这些方法应在“工具”之外使用,以便他们可以调用其他类的方法,如:
class customTools(QtGui.QToolBar):
"""represents a custom QToolBar"""
...
def action_one(self):
some_other_classes.function()
现在,我被困在这里:
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...
答案 0 :(得分:0)
行。这适用于现在:
里面的课堂方法:
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()
添加为classmethod:
setattr(tools, action_one.__name__, MethodType(action_one, tools, type(tools)))
(在此处找到:http://dietbuddha.blogspot.com/2012/12/python-metaprogramming-dynamically.html,不要忘记积分,但是......)