PyQt5 series of tutorials (34) Basic use of QComboBox

Software and hardware environment

  • Windows 10 64bit
  • Anaconda3 with python 3.8
  • PyQt5 5.15

Introduction

QComboBox is a drop-down list control that provides multiple options for users to choose, which is very common in practical applications.

The commonly used methods of QCombobox are as follows

method Function
addItem() Add a drop down option
addItems() Add multiple drop-down options, parameter use list
clear() Remove all dropdown options
count() Returns the number of dropdown options
currentText() Returns the text of the selected option
itemText(i) Returns the text of the option with index i
currentIndex() Returns the index value of the selected option
itemText(i) Returns the text of the option with index i
setItemText(index,text) Modify the text whose index value is index

Common signals of QComboBox

Signal Function
Activated This signal is emitted when a dropdown option is selected
currentIndexChanged Emitted when the index of the drop-down option changes
highlighted This signal is emitted when the drop-down option is selected

Practical

For interface design, we still use the designer to do it, drag a label and combo box control to the main window, and adjust the position, size, font size, etc.

The following is the core code, which is also relatively easy to understand, refer to the comments between the codes

 import sys from PyQt5.QtWidgets import QMainWindow, QApplication from ui import Ui_MainWindow class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) # 增加单个选项self.comboBox.addItem("Python") self.comboBox.addItem("Java") # 增加多个选项self.comboBox.addItems(["C", "C++", "Javascript"]) # 绑定信号和槽# 当下拉选项的index发生变化,才发射这个信号,比如连续选中同一个选项,这个信号就不会发射self.comboBox.currentIndexChanged.connect(self.on_item_selected) # 和currentIndexChanged不同的是,即使前后选择的是同一个选项,信号也会被发射self.comboBox.activated.connect(self.on_activated) # 当焦点在下拉选项上时,信号被发射self.comboBox.highlighted.connect(self.on_highlighted) def on_item_selected(self): print("{}: {}, index={}, total count={}".format(self.label.text(), self.comboBox.currentText(), self.comboBox.currentIndex(), self.comboBox.count())) def on_activated(self): print('on_activated.') def on_highlighted(self): print('on_highlighted.') if __name__ == '__main__': app = QApplication(sys.argv) windows = MainWindow() windows.show() sys.exit(app.exec_())

The final execution effect is as follows

Source code download

https://github.com/xugaoxiang/learningPyQt5

PyQt5 series of tutorials

For more PyQt5 tutorials, please move

https://xugaoxiang.com/category/python/pyqt5/

This article is reprinted from https://xugaoxiang.com/2022/10/20/pyqt5-34-qcombobox/
This site is for inclusion only, and the copyright belongs to the original author.