dissidia
dissidia

Reputation: 1581

Accessing QComboBox index values

I have a comboxbox which contains 2 items - Method01, Method02 How can I tell my code to execute Method01Func when Method01 is selected, likewise for Method02 too?

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

I tried to code it in something similar when accessing in a list - [0],[1]... but I was bumped with errors

Upvotes: 1

Views: 681

Answers (2)

a_manthey_67
a_manthey_67

Reputation: 4306

alternatively You can send the current items text with the signal:

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

and check it in the slot:

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

Upvotes: 0

user3419537
user3419537

Reputation: 5000

One way to do it is to make use of the userData parameter when calling addItem(), and pass in a reference to the function you want that item to call.

Here's a simple example:

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

Upvotes: 1

Related Questions