blaz
blaz

Reputation: 4248

PyQt: Get the highlighted index from QComboBox

I want to obtain the index of the highlighted item in the QComboBox. How can I access to this variable?

The sample code I have:

    ...
    self.combobox = QtWidgets.QComboBox()
    self.combobox.addItems(['a', 'b', 'c'])
    self.combobox.highlighted.connect(self.return_higlighted_index)
    ...

def return_highlighted_index(self):
    print('The current highlighted index is: ', '?')

Upvotes: 0

Views: 1550

Answers (2)

blaz
blaz

Reputation: 4248

I found the solution, the code should be modified as follows

    ...
    self.combobox = QtWidgets.QComboBox()
    self.combobox.addItems(['a', 'b', 'c'])
    self.combobox.highlighted[int].connect(self.return_higlighted_index)
    ...

def return_highlighted_index(self, param):
    print('The current highlighted index is: ', param)

Upvotes: 0

2006pmach
2006pmach

Reputation: 371

Instead of

self.combobox.highlighted.connect(self.return_higlighted_index)

try something like this (not tested)

self.combobox.activated[str].connect(self.return_higlighted_index)

def return_highlighted_index(self, combobox_entry):
    idx = self.combobox.findText(combobox_enty)
    print('The current highlighted index is: {}'.format(idx))

So you connect your method return_highlighted_index to the combobox whenever it is changed it passes its current highlighted string to the method return_highlighted_index as combobox_entry with return_highlighted_index() you should be able to obtain the index.

Upvotes: 1

Related Questions