You can have a listbox, selectbox or combobox with QComboBox. To use this widget, import QComboBox from PyQt5.QtWidgets.

Typically you’d see this widget when a user needs to choose from a select number of items, like country or contract.

Related Course: Create GUI Apps with Python PyQt5

QComboBox

Create a listbox

You can create a list box with these lines:

1
2
combo = QComboBox(self)
combo.addItem("Apple")

The method addItem adds an option to the list box. You can call that as many times as you need to with different options.

To connect a listbox change with a method, you can use this:

1
combo.activated[str].connect(self.onChanged)      

pyqt combobox

Example

The code below adds a combobox to a window. Once you select one of the options presented in the combo box, the label values changes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QComboBox, QPushButton

class Example(QMainWindow):

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

combo = QComboBox(self)
combo.addItem("Apple")
combo.addItem("Pear")
combo.addItem("Lemon")

combo.move(50, 50)

self.qlabel = QLabel(self)
self.qlabel.move(50,16)

combo.activated[str].connect(self.onChanged)

self.setGeometry(50,50,320,200)
self.setWindowTitle("QLineEdit Example")
self.show()

def onChanged(self, text):
self.qlabel.setText(text)
self.qlabel.adjustSize()

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

If you are new to Python PyQt, then I highly recommend this book.

Download Examples