Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 719
Collaptic Avatar asked Jan 26 '26 01:01

Collaptic


1 Answers

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
like image 72
Mel Avatar answered Jan 27 '26 14:01

Mel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!