PyQt QComboBox

QComboBox.

QComboBox is a widget that allows you to take up a small space, provide multiple options, and choose one of them.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QComboBox

class MyApp(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.lbl = QLabel('Option1', self)
        self.lbl.move(50, 150)

        cb = QComboBox(self)
        cb.addItem('Option1')
        cb.addItem('Option2')
        cb.addItem('Option3')
        cb.addItem('Option4')
        cb.move(50, 50)

        cb.activated[str].connect(self.onActivated)

        self.setWindowTitle('QComboBox')
        self.setGeometry(300, 300, 300, 200)
        self.show()

    def onActivated(self, text):
        self.lbl.setText(text)
        self.lbl.adjustSize()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

We created one label and a combobox widget, and the items selected in the combo box appeared on the label.

pyqt combobox

Related course: Create Desktop Apps with Python PyQt5

Description

cb = QComboBox(self)
cb.addItem('Option1')
cb.addItem('Option2')
cb.addItem('Option3')
cb.addItem('Option4')
cb.move(50, 50)

We created one QComboBox widget and added four options to choose from using the addItem() method.

cb.activated[str].connect(self.onActivated)

When the option is selected, the onActivated() method is called.

def onActivated(self, text):

self.lbl.setText(text)
self.lbl.adjustSize()

Make the text of the selected item appear on the label, and use the adjustSize() method to automatically resize the label.

Related course: Create Desktop Apps with Python PyQt5