PyQt - QComboBox Widget



A QComboBox object presents a dropdown list of items to select from. It takes minimum screen space on the form required to display only the currently selected item.

A Combo box can be set to be editable; it can also store pixmap objects. The following methods are commonly used −

Given below are the most commonly used methods of QComboBox.

Sr.No. Methods & Description
1

addItem()

Adds string to collection

2

addItems()

Adds items in a list object

3

Clear()

Deletes all items in the collection

4

count()

Retrieves number of items in the collection

5

currentText()

Retrieves the text of currently selected item

6

itemText()

Displays text belonging to specific index

7

currentIndex()

Returns index of selected item

8

setItemText()

Changes text of specified index

QComboBox Signals

Sr.No. Methods & Description
1

activated()

When the user chooses an item

2

currentIndexChanged()

Whenever the current index is changed either by the user or programmatically

3

highlighted()

When an item in the list is highlighted

Example 1: Basic QComboBox Widget

To create a basic QComboBox widget in PyQt6, you should first need to import the necessary modules and then instantiate the QComboBox class. In this example, we create a simple main window containing a QComboBox with three predefined options.

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QComboBox

class MyWindow(QMainWindow):
   def __init__(self):
      super().__init__()
      self.setWindowTitle("QComboBox Example")
      self.setGeometry(200, 200, 300, 200)

      combobox = QComboBox(self)
      combobox.addItem("Option 1")
      combobox.addItem("Option 2")
      combobox.addItem("Option 3")
      combobox.move(50, 50)

app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec())

Output

The above code produces the following output −

pyqt Qcombobox basic usage

Example 2: Editable ComboBox

By default, QComboBox is not editable, meaning users can only select from the provided options. However, you can enable editing to allow users to input custom values.

In this example, we set the editable property of the QComboBox to True, enabling users to input custom values in addition to selecting from the provided options.

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QComboBox

class MyWindow(QMainWindow):
   def __init__(self):
      super().__init__()
      self.setWindowTitle("Editable QComboBox")
      self.setGeometry(200, 200, 300, 200)

      combobox = QComboBox(self)
      combobox.setEditable(True)
      combobox.addItem("Option 1")
      combobox.addItem("Option 2")
      combobox.addItem("Option 3")
      combobox.move(50, 50)

app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec())

Output

The above code produces the following output −

pyqt qcombobox example 2
Advertisements