Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 948
alphanumeric Avatar asked Apr 01 '14 22:04

alphanumeric


People also ask

How do I add items to QComboBox in Python?

A combobox can be created with the QComboBox class. Items are added using the class method addItem, followed by a string parameter. Sometimes its called a listbox, as it shows a list of items a user can select from. If you want a user to choose from a set of items, the listbox is the best option.

How do I add items to QComboBox?

A combobox can be populated using the insert functions, insertItem() and insertItems() for example. Items can be changed with setItemText(). An item can be removed with removeItem() and all items can be removed with clear().


1 Answers

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.

like image 56
ekhumoro Avatar answered Sep 29 '22 03:09

ekhumoro