Thursday, 19 September 2019

Working with Item Selection from Dropdown List (QComboBox Widget)


Hi Guys, welcome back to my Python Blog. Today, I am going to write a complete guide for the QComboBox widget to be used as a dropdown list. Recall, in previous posts, we are designing application GUI in Qt. Similarly, we design another GUI for this post in Qt as well.

Open PyCharm from Start menu, once it is opened. Start PyQt5Designer from Terminal. 

Create a new GUI file, which contains a title label 'QComboBox Example', a 'QComboBox' widget from the left panel and a label below the widget. It is shown in the figure below.


Now, you can add items of the dropdown list in many ways. I am using the simplest one, by right-clicking on the QComboBox and select 'Edit Items...' option as shown in the following figure.


A new pop-up window will be opened, by clicking on bottom-left green '+' button, it will add 'New Item' of the list. You can enter any item value as per your need.


For instance, I entered five games on the list including Cricket, Hocky, Soccer, Tennis and Table Tennis.



After entering the list items, I clicked the OK button. By default, the first item will be displayed in the dropdown list.


From the 'QComboBox' properties, I entered the objectName as 'gamesComboBox' and saved this GUI as 'combo.ui' file.



Now, going straight to the Python. I load the 'combo.ui' file in the 'init_ui' method. Here, we need to observe the item change from the dropdown list as the user selects. Therefore, 'currentTextChanged' will be called a user selects any item. Next, is the 'on_combobox_changed' method containing if-else statements and will be invoked particularly related to any item selection. Whenever the user chooses any item, it will display the selected item to the label below this dropdown list.


Run the Python file, it will display the GUI as under:


Click the dropdown list, it displays the games list.


I selected the Tennis game, this game is displayed on the label as shown below:


It is pretty simple to work with QComboBox widget. That's all about this post. 

Cheers!