所以我正在生成基於我的系統上的一些文件的選項菜單。我有一個列表對象,我需要在菜單中動態生成一個選項,並且需要能夠讓正在進行創建的函數知道使用哪個對象。經過一些研究後,我發現下面的帖子。我不能評論,因爲我的代表還不高: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,我認爲我正在做的事情是正確的。
謝謝@ekhumoro會嘗試更新的安裝 – jspada