在 lineedit 中键入值,然后通过单击按钮将其添加到组合框? PyQt4

Type values in lineedit and then add it to a comboBox by clicking a button? PyQt4

我想通过单击按钮(一次一个值)将在 lineedit 中键入的多个值添加到组合框。我的示例代码如下:

import os, sys

import PyQt4
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Example(QWidget):
    def __init__(self, parent = None):
        super().__init__()

        self.grid = QGridLayout()
        self.setLayout(self.grid)
        btn = QPushButton()
        le = QLineEdit()
        combo = QComboBox()

        self.grid.addWidget(btn, 0, 0)
        self.grid.addWidget(le, 0 , 1)
        self.grid.addWidget(combo, 0, 2)


        self.show()

def main():
    app = QApplication(sys.argv)
    main = Example()
    main.show()
    sys.exit(app.exec_())

main()

如果有人知道怎么做,请告诉我。赞赏!!

解决方案很简单,您应该分析的第一件事是在哪个事件之前完成操作,在您的情况下,当发出点击信号时,以便连接插槽并在其中管理逻辑。获取文本,使用QLineEdittext()方法,用addItem()方法添加到QComboBox中,我加了一个小逻辑验证不能添加非空文本并且不重复项目

class Example(QWidget):
    def __init__(self, parent = None):
        super().__init__()

        self.grid = QGridLayout()
        self.setLayout(self.grid)
        self.btn = QPushButton()
        self.le = QLineEdit()
        self.combo = QComboBox()

        self.grid.addWidget(self.btn, 0, 0)
        self.grid.addWidget(self.le, 0 , 1)
        self.grid.addWidget(self.combo, 0, 2)

        self.btn.clicked.connect(self.onClicked)

    def onClicked(self):
        text = self.le.text()
        # the text is not empty
        if text != "":
            # get items of combobox
            items = [self.combo.itemText(i) for i in range(self.combo.count())] 
            # Add if there is no such item
            if text not in items: 
                self.combo.addItem(text)

变量只能在创建的方法范围内访问,因此不适合将小部件设为仅变量,而是 class 的属性,因为它们可以在任何方法中访问class。为此,我们必须只放 self.