2016-08-15 32 views
1

我使用for循环像这样创建的QAction对象列表中单击所触发的功能参数:传递的QAction对象,调用triggered.connect()在后,我上的QAction

class some_class: 
    self.tabs = [] 

    for self.i in range(0,10): 
    self.tabs[self.i] = QtGui.QAction("New", self) 
    self.tabs[self.i].triggered.connect(self.some_function) 

    def some_function(self): 
    print self.i 

每当我点击任何创建的选项卡,它只会触发选项卡[9]并仅打印“9”。

那么如何传递的QAction对象本身在由此引发some_function()

回答

2

缓存的some_function指数作为默认参数:

for index in range(0, 10): 
    action = QtGui.QAction("New", self) 
    action.triggered.connect(
     lambda checked, index=index: self.some_function(index)) 
    self.tabs.append(action) 

... 

def some_function(self, index): 
    action = self.tabs[index] 
    print(action.text()) 
+0

action.triggered.connect( 拉姆达*指定参数时,指数= index:self.some_function(index)) 产生语法错误 –

+0

@SahilGupta。这对我来说可以。没有任何错误。你一定已经改变了我的代码。什么是语法错误? – ekhumoro

+0

它适用于action.triggered.connect(lambda:self.some_function(index))&也有(lambda * args:self.some_function(index)),但会产生语法错误\t action.triggered.connect(lambda * args ,index = index:self.some_function(index))。感谢您讲述使用lambda函数。 –