简体   繁体   English

PyQt4,从comboBox获取当前文本

[英]PyQt4, getting current text from comboBox

I have a pretty simple GUI with a comboBox, with 4 items. 我有一个带有comboBox的非常简单的GUI,其中包含4个项目。
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. 这四个项目中的每一个都做不同的事情,需要在启用/禁用QLineEdit框以及能够基于当前选择添加占位符文本方面链接到QLineEdit框。

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, ie self.lineEdit_5 = QtGui.QLineEdit() 当然,其中self.lineEditsQLineEdit ,即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 PS:这与完整的代码相去甚远,它已大大简化,因此易于阅读,如果您需要更多信息,请告诉我

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). 每当在comboBox选择了新项目时,都会发出currentIndexChanged(const QString & text)信号( text是所选新项目的文本)。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM