我有一個包含2項comboxbox - Method01, Method02
怎麼能告訴我在選擇Method01
我的代碼執行Method01Func
,同樣爲Method02
呢?訪問QComboBox指數值
self.connect(self.exportCombo, SIGNAL('currentIndexChanged(int)'), self.Method01Func)
我想它類似的代碼放在一個list
訪問時 - [0],[1] ...但我被撞有錯誤
我有一個包含2項comboxbox - Method01, Method02
怎麼能告訴我在選擇Method01
我的代碼執行Method01Func
,同樣爲Method02
呢?訪問QComboBox指數值
self.connect(self.exportCombo, SIGNAL('currentIndexChanged(int)'), self.Method01Func)
我想它類似的代碼放在一個list
訪問時 - [0],[1] ...但我被撞有錯誤
一種方式做到這一點是利用調用addItem()
時參數爲userData
,並傳遞對您希望該項目調用的函數的引用。
這裏有一個簡單的例子:
import sys
from PyQt4 import QtCore, QtGui
def Method01Func():
print 'method 1'
def Method02Func():
print 'method 2'
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
widget = QtGui.QWidget()
self.combo = QtGui.QComboBox()
self.combo.addItem('Method 1', Method01Func)
self.combo.addItem('Method 2', Method02Func)
self.combo.currentIndexChanged.connect(self.execute_method)
layout = QtGui.QVBoxLayout(widget)
layout.addWidget(self.combo)
self.setCentralWidget(widget)
@QtCore.pyqtSlot(int)
def execute_method(self, index):
method = self.combo.itemData(index).toPyObject()
method()
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
或者,你可以發送信號當前項目中的文字:
self.exportCombo.currentIndexChanged[str].connect(self.execute_method)
,並檢查它的插槽:
def execute_method(self, text):
(self.Method01Func() if text == 'Method01' else self.Method02Func())