Python

How to Use PyQt QComboBox

A ComboBox is used to select one item from a list of items, much like the radio button. The QComboBox class of PyQt is used to create drop-down lists using Python script. It brings up a list of items for the user to select. The items of the ComboBox can be added, changed, and removed using the script. Multiple items can be selected like the CheckBox button from the list of items from the ComboBox then it is called ListBox. This tutorial shows you how to use QComboBox to create a drop-down list in Python.

QComboBox Methods

The QComboBox class contains many methods for performing various tasks related to ComboBox. Some of the more commonly used methods of this class are described below:

Method Name Purpose
count() Used to count the total number of items in the list.
addItem() Used to add a single new item to the list.
addItems() Used to add multiple items to the list.
itemText() Used to read the text of a particular item based on an index.
setItemText() Used to set the text of a particular item based on an index.
currentText() Used to read the text of the selected item.
currentIndex() Used to read the index of the selected item.
clear() Used to delete all items from the list.
highlighted() Used when an item in the list is highlighted.
activated() Used when an item is selected by the user.
currentIndexChanged() Used when the item in the list has changed.

ComboBox Usage

The following sections provide examples that explain some different uses of the ComboBox using the QComboBox module of the PyQt library.

Example 1: Create a Simple Drop-Down List

This example shows you how to create a simple drop-down list using the QComboBox class. Here, a drop-down list of five elements is created and is attached to a custom function that will print the selected value from the list. One label is used in the function of the drop-down list to display static text, and another label is used below the drop-down list to show the selected value.

# Import necessary modules

import sys

from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QVBoxLayout, QComboBox)

# Declare class to create the ComboBox

class ComboExample(QWidget):

    def __init__(self):

        super().__init__()


        # Set the label before the ComboBox

        self.topLabel = QLabel('Select your favorite programming language:', self)


        # Define the combobox with items

        combobox = QComboBox(self)

        combobox.addItem('PHP')

        combobox.addItem('Python')

        combobox.addItem('Perl')

        combobox.addItem('Bash')

        combobox.addItem('Java')


        # Set the label after the ComboBox

        self.bottomLabel = QLabel('', self)

        self.bottomLabel.adjustSize()


        # Define vartical layout box

        v_layout = QVBoxLayout()

        v_layout.addWidget(self.topLabel)

        v_layout.addWidget(combobox)

        v_layout.addWidget(self.bottomLabel)


        # Call the custom method if any item is selected

        combobox.activated[str].connect(self.onSelected)


        # Set the configurations for the window

        self.setContentsMargins(20, 20, 20, 20)

        self.setLayout(v_layout)

        self.move(800, 300)

        self.setWindowTitle('Use of ComboBox')


    # Custom function to read the value of the selected item

    def onSelected(self, txtVal):

        txtVal = "\nYou have selected: " + txtVal

        self.bottomLabel.setText(txtVal)


# Create app object and execute the app

app = QApplication(sys.argv)

combobox = ComboExample()

combobox.show()

app.exec()

If the user clicks on the drop-down list after executing the script, the following list will appear.

If the user selects the value Bash from the drop-down list, the value of the second label will be changed to ‘You have selected: Bash.

Example 2: Create a ComboBox Using the List

In the previous example, the drop-down list was created with static data using the addItem() method of the QComboBox class. This example shows you how to add multiple items in the drop-down list by defining a Python list. First, we will add static text to the first item of the drop-down list using the addItem() method. Next, we will define a list of five elements in the script, and we will add these elements to the drop-down list using the addItems() method. A custom function is attached to the drop-down list to display the message in the label based on the user selection.

# Import necessary modules

import sys

from PyQt5.QtWidgets import *

# Declare the class to create combobox by using list data

class ComboExample(QMainWindow):

    def __init__(self):

        super().__init__()


        # Set the tittle of the window

        self.setWindowTitle("ComboBox with List data ")

        # Set the geometry for the window

        self.setGeometry(100, 100, 350, 150)


        # Create combobox

        self.combobox = QComboBox(self)

        # Set the geometry for the combobox

        self.combobox.setGeometry(30, 30, 200, 30)


        # Define list items for the combobox

        src_engines = ["google.com", "yahoo.com", "ask.com", "baidu.com", "yandex.com"]

        # Enable the editable option of the combobox

        self.combobox.setEditable(True)

        # Set the first item for the combobox

        self.combobox.addItem("Select Search Engine")

        # Add multiple items in the combobox using list

        self.combobox.addItems(src_engines)


        # Define label at the bottom of the combobox to provide message for the user

        self.msgLabel = QLabel('', self)

        # Set the geometry for the label

        self.msgLabel.setGeometry(30, 60, 290, 60)


        # Call the custom function when any item is selected

        self.combobox.activated[str].connect(self.onClicked)


        # Move the position of the window

        self.move(800, 400)

        # Display the Window

        self.show()


    # Define a method to handle the click event of the Combobox

    def onClicked(self, val):

        # Check any item is selected by the user or not

        if val == "Select Search Engine":

            message = "You have selected nothing."

        else:

            message = "Your favorite search engine is " + val


        # Display the message text in the label

        self.msgLabel.setText(message)

        # Display the message in the console

        print(message)


# Create the app object

app = QApplication(sys.argv)

# Create an object of the class object

combo = ComboExample()

# Execute the app

app.exec()

If the user clicks the drop-down list after executing the script, then the following list will appear.

If the user selects any item except the first item in the drop-down list, then the selected value will be shown in the label by combining with the other text.

If the user selects the first item in the drop-down list, then the value, ‘You have selected nothing’ will be shown in the label.

Conclusion

This article showed you how to create and use drop-down lists in Python using the QComboBox class using simple examples to help you to better understand the use of this class.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.