Search code examples
pythonqtpysideqcombobox

How to use a QCombobox selection in a if loop?


I'm new to GUI's and I'm trying to make the user's choice in a combobox change the outcome of my program.

Here's my Combobox:

self.popupItems1 = ("Option 1","Option 2")
self.popup1 = QtGui.QComboBox(self)
self.popup1.addItems(self.popupItems1)
self.popup1.setCurrentIndex(self.popupItems1.index("Option 1"))
self.popup1.move(10, 220)

I've done quite a lot of research but I can't seem to to figure this out, I'm guessing I should use something like this?

if self.popupItems1 == 'Option 1':
     do_something()
else:
     do_something_else()

Thank you in advance for any help!


Solution

  • To get the currently selected text in a QComboBox use the method currentText(), and if you want to get the index then use the method currentIndex().

    For example if your QComboBox is referenced by self.popup1 then to get the selected text use :

    text = self.popup1.currentText()
    

    You can also get the index using the other method.

    What you are looking for might be this :

    if self.popup1.currentIndex() == 0 : # The first option
        do_something()
    else : # Any other option
        do_something_else()
    

    For more informations check the documentation of QComboBox.