Collaptic
Collaptic

Reputation: 307

PyQt4, getting current text from comboBox

I have a pretty simple GUI with a comboBox, with 4 items.
Each of these four items do separate things, and need to be linked to QLineEdit boxes in terms of enabling/disabling the QLineEdit boxes, as well as being able to add placeholder text based on the current selection.

Code:

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        self.comboBox = QtGui.QComboBox(self.centralwidget)
        self.comboBox.setGeometry(QtCore.QRect(10, 10, 201, 26))
        self.comboBox.setObjectName(_fromUtf8("comboBox"))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))

        if self.comboBox.currentText() == 'Item1':
            self.lineEdit_5.setDisabled(True)
            self.lineEdit_4.setText('0')  

    def retranslateUi(self, MainWindow):
        self.comboBox.setItemText(0, _translate("MainWindow", "Item1", None))
        self.comboBox.setItemText(1, _translate("MainWindow", "Item2", None))
        self.comboBox.setItemText(2, _translate("MainWindow", "Item3", None))
        self.comboBox.setItemText(3, _translate("MainWindow", "Item4", None))

Where the self.lineEdits are QLineEdit of course, i.e. self.lineEdit_5 = QtGui.QLineEdit()

What am I doing wrong here?

PS: This is far from the full code, this is drastically simplified so its easy to read, let me know if you need more info

Upvotes: 3

Views: 1106

Answers (1)

Mel
Mel

Reputation: 6075

You need to use signal and slots.

Whenever a new item is selected in the comboBox, the signal currentIndexChanged(const QString & text) is emitted (text being the text of the new item selected). You can connect a method to this signal, and do whatever you need with the line edits.

    self.comboBox.currentIndexChanged[str].connect(self.onChange)

def onChange(self, newText):
    if newText=="Item 1":
        #do this
    else:
        #do that

Upvotes: 3

Related Questions