2015-05-25 60 views
0

所以我正在生成基於我的系統上的一些文件的選項菜單。我有一個列表對象,我需要在菜單中動態生成一個選項,並且需要能夠讓正在進行創建的函數知道使用哪個對象。經過一些研究後,我發現下面的帖子。我不能評論,因爲我的代表還不高:How to pass arguments to callback functions in PyQt麻煩理解信號映射器PyQt

當我運行這個信號映射器不工作的權利。它甚至沒有正確調用handleButton。有關如何正確使用信號映射器的任何想法?

from PyQt4 import QtGui, QtCore 

class Window(QtGui.QMainWindow): 
    def __init__(self): 
     QtGui.QMainWindow.__init__(self) 
     self.mapper = QtCore.QSignalMapper(self) 
     self.toolbar = self.addToolBar('Foo') 
     self.toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) 
     for text in 'One Two Three'.split(): 
      action = QtGui.QAction(text, self) 
      self.mapper.setMapping(action, text) 
      action.triggered.connect(self.mapper.map) 
      self.toolbar.addAction(action) 
     self.mapper.mapped['QString'].connect(self.handleButton) 
     self.edit = QtGui.QLineEdit(self) 
     self.setCentralWidget(self.edit) 

    def handleButton(self, identifier): 
     print 'run' 
     if identifier == 'One': 
      text = 'Do This' 
      print 'Do One' 
     elif identifier == 'Two': 
      text = 'Do That' 
      print 'Do Two' 
     elif identifier == 'Three': 
      print 'Do Three' 
      text = 'Do Other' 
     self.edit.setText(text) 

if __name__ == '__main__': 

    import sys 
    app = QtGui.QApplication(sys.argv) 
    window = Window() 
    window.resize(300, 60) 
    window.show() 
    sys.exit(app.exec_()) 

編輯:

我發現,通過使用舊式信號/槽連接,這是固定的:

#action.triggered.connect(self.mapper.map) 
self.connect(action, QtCore.SIGNAL("triggered()"), self.mapper, QtCore.SLOT("map()")) 

#self.mapper.mapped['QString'].connect(self.handleButton) 
self.connect(self.mapper, QtCore.SIGNAL("mapped(const QString &)"), self.handleButton) 

上午我錯誤地使用新式連接?

基於this post以及我發佈的original link,我認爲我正在做的事情是正確的。

回答

1

最初的示例代碼(我寫的),對於我使用Python2或Python3以及幾個不同的最新版本的PyQt4來說完美無缺。但是,如果我使用的是PyQt4(4.7)的真正舊版本,則不再調用處理程序。

這樣做的原因(和解決方案)在迴應郵件列表後給你鏈接到:

它實際上是用QSignalMapper.map()的一個問題從 代理,而不是被稱爲新式連接。

的解決方法是明確指定的信號是地圖()兼容 ...

self.b1.clicked[()].connect(self.mapper.map) 

今晚的PyQt的快照將有約決定它需要使用之前找到一個可用的Qt插槽 更聰明代理,以便解決方法 將不是必需的。

有一些信號(如clickedtriggered)總是發送一個默認值,除非你明確要求,否則。與舊式的信號,你可以指定沒有默認與SIGNAL("triggered()")超載,但與新型信號,你必須做這樣的:

action.triggered[()].connect(self.mapper.map) 

不過,這只是必要的很老的版本PyQt4 - 潛在的問題在2010年得到修復(不知道確切的版本,但4.8應該沒問題)。

+0

謝謝@ekhumoro會嘗試更新的安裝 – jspada