PyQt5 - How to add an item to the ComboBox?

PyQt5 - How to add an item to the ComboBox?

Using PyQt5, adding items to a QComboBox widget is straightforward. Here's a simple step-by-step guide on how to do this:

  • Install PyQt5: If you haven't already installed PyQt5, you can do so using pip:
pip install pyqt5 
  • Basic Example: Here's a basic example of creating a PyQt5 application with a QComboBox, and adding items to it:
import sys from PyQt5.QtWidgets import QApplication, QWidget, QComboBox, QVBoxLayout class ComboBoxApp(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): layout = QVBoxLayout() # Create a combo box self.combo = QComboBox(self) # Add items to the combo box self.combo.addItem("Option 1") self.combo.addItem("Option 2") self.combo.addItem("Option 3") # Add combo box to layout layout.addWidget(self.combo) # Set the layout for the widget self.setLayout(layout) # Window properties self.setWindowTitle('ComboBox Example') self.setGeometry(300, 300, 300, 200) if __name__ == '__main__': app = QApplication(sys.argv) ex = ComboBoxApp() ex.show() sys.exit(app.exec_()) 

In the example above:

  • We create a QComboBox object.
  • We use the addItem() method of the QComboBox to add individual items.
  • The combo box is then added to a QVBoxLayout, which is then set as the layout for the main widget.

You can also add multiple items at once using the addItems() method, which takes a list of strings:

self.combo.addItems(["Option 1", "Option 2", "Option 3"]) 

This is the basic approach to adding items to a QComboBox in PyQt5.


More Tags

ieee-754 auth0 windows-vista ads local logcat cgpoint equals docker-desktop graphviz

More Programming Guides

Other Guides

More Programming Examples