Search code examples
pythonbuttonpyqtqcomboboxqlineedit

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


I want to add multiple value typed in lineedit to a combobox by clicking a button (one value at one time). My sample codes are as below:

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()

If anyone knows how to do it, pls let me know. Appreciated!!


Solution

  • The solution is simple, the first thing you should analyze is before which event the action is done, in your case when the clicked signal is emitted, so that a slot is connected and in it we manage the logic. To get the text, use the text() method of QLineEdit, and add it to the QComboBox with the addItem() method, I added a small logic to validate and can not add non-empty text and also not to repeat the items

    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)
    

    The variables can only be accessed in the scope of the method that is created so it is not appropriate to make the widget only variables, but attributes of the class since they are accessible in any method of the class. For this we must only put self.