alphanumeric
alphanumeric

Reputation: 19329

How to set QComboBox to item from item's text in PyQt/PySide

Is it possible to set QComboBox to an item knowing only an item's text value? I am trying to avoid looping through for i in range(myCombobox.count()) just to find an item's index so it could be used to set the current index.

Upvotes: 39

Views: 77178

Answers (1)

ekhumoro
ekhumoro

Reputation: 120608

Yes, there is QComboBox.findText, which will return the index of the matched item (or -1, if there isn't one). By default, the search does exact, case-sensitive matching, but you can tweak the behaviour by passing some match-flags as the second argument. For example, to do case-insensitive matching:

    index = combo.findText(text, QtCore.Qt.MatchFixedString)
    if index >= 0:
         combo.setCurrentIndex(index)

There is also an equivalent findData method that matches by the item's data.

Upvotes: 79

Related Questions