2014-10-10 5 views
1

나는이 개 항목을 포함하는 comboxbox는 한 - Method01, Method02 어떻게 Method01을 선택하면 내 코드가 너무 Method02에 대한 마찬가지로, Method01Func를 실행 알 수 있습니까? list에 액세스 할 때액세스 QComboBox 인덱스 값

self.connect(self.exportCombo, SIGNAL('currentIndexChanged(int)'), self.Method01Func) 

내가 비슷한에 코딩을 시도 - [0], [1] ... 그러나 나는이 오류와 함께 할

답변

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_() 
0

이 대안으로 당신은 신호 현재 항목의 텍스트 보낼 수 있습니다 :

self.exportCombo.currentIndexChanged[str].connect(self.execute_method) 

를 슬롯에 그것을 확인 :

def execute_method(self, text): 
    (self.Method01Func() if text == 'Method01' else self.Method02Func()) 
다음

은 간단한 예제