Search code examples
pythonqtpyqtqt-designer

How to get value of QtComboBox?


I am creating a QGIS plugin using a QGIS plugin builder template.

def __init__(self, iface):

    #some code
    self.dlg = QtGui.QDialog();
    main_layout = QtGui.QVBoxLayout()
    city = QtGui.QComboBox()
    city.addItem("Tucson")
    city.addItem("Austin")
    city_label = QtGui.QLabel("City", city)

    buttons = QDialogButtonBox(
        QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
        Qt.Horizontal, self.dlg)
    buttons.accepted.connect(self.dlg.accept)
    buttons.rejected.connect(self.dlg.reject)

    main_layout.addWidget(city)
    self.dlg.setLayout(main_layout)

def run(self):
    self.dlg.show()
    result = self.dlg.exec_()
    if result:
        selected_city = city.currentText()
        print selected_city
        pass

I get an error message because "city" is not recognized. How can I get the selected value in the QTComboBox whenever the user changes the value? Is there a more simple way to create the UI? I basically just need something that will update the city (and some other) information every time the user selects a different value, and change the options in the combo box every 5 minutes.


Solution

  • Where you say 'city' you should say 'self.city' so that city is attached to the object. Then later you can get its text as 'self.city.currentText()'.