Search code examples
pythonpython-3.xpyqtpyqt5qcombobox

QComboBox setCurrentIndex by text


I have a ComboBox with different values inside: Yes, No.

Can I set the ComboBox by a value I receive from an input? I don't want to set it by index#. I also want to try to stay away from if statements.

enter image description here

I've tried something like this:

    self.UnlHE_Drop = QtWidgets.QComboBox(self.scrollAreaWidgetContents)
    self.UnlHE_Drop.setObjectName("UnlHE_Drop")
    self.UnlHE_Drop.addItem("")
    self.UnlHE_Drop.setItemText(0, "")
    self.UnlHE_Drop.addItem("")
    self.UnlHE_Drop.addItem("")

def retranslateUi(self, VlS):
    _translate = QtCore.QCoreApplication.translate
    VlS.setWindowTitle(_translate("VlS", "Value"))
    self.UnlHE_Drop.setItemText(1, _translate("VlS", "Yes"))
    self.UnlHE_Drop.setItemText(2, _translate("VlS", "No"))
    self.UnlHE_DropInfo = QInputDialog.getText(None, 'Answer:', 'Yes or No:')
    self.UnlHE_Drop.setCurrentIndex(self.UnlHE_Drop.findText(self.UnlHE_DropInfo))

Solution

  • First you have to add items to the QComboBox since when you use findText you are looking for those items, Another thing is that QInputDialog.getText returns a tuple, the first is the value entered and the second is a bool that indicates whether you pressed yes or no.

    self.UnlHE_Drop = QtWidgets.QComboBox(self.scrollAreaWidgetContents)
    self.UnlHE_Drop.addItems(["Yes", "No"])
    UnlHE_DropInfo, ok = QInputDialog.getText(None, 'Answer:', 'Yes or No:')
    if ok:
        self.UnlHE_Drop.setCurrentText(UnlHE_DropInfo)