PyQt5 - How to add model to ComboBox

PyQt5 - How to add model to ComboBox

In PyQt5, a QComboBox widget can be populated with items using a model. Typically, a QStringListModel or a custom model derived from QAbstractListModel or QAbstractItemModel is used for this purpose. Here's a guide on how to add a model to a QComboBox in PyQt5:

Step 1: Import PyQt5 Modules

First, import the necessary modules from PyQt5:

from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QComboBox from PyQt5.QtCore import QStringListModel import sys 

Step 2: Create a Model

Create a model (e.g., QStringListModel) and populate it with a list of items:

model = QStringListModel() model.setStringList(["Item 1", "Item 2", "Item 3", "Item 4"]) 

Step 3: Create a QComboBox and Set Its Model

Create a QComboBox widget and set the model created in the previous step:

combo_box = QComboBox() combo_box.setModel(model) 

Step 4: Create a Main Window

Now, create a main window and add the combo box to it:

class MainWindow(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): layout = QVBoxLayout(self) layout.addWidget(combo_box) self.setLayout(layout) self.setWindowTitle('QComboBox with Model') self.setGeometry(300, 300, 300, 200) 

Step 5: Start the Application

Finally, create an instance of QApplication and start the event loop:

app = QApplication(sys.argv) main_window = MainWindow() main_window.show() sys.exit(app.exec_()) 

Complete Example

Here's the complete code combining all the steps:

from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QComboBox from PyQt5.QtCore import QStringListModel import sys # Create the model model = QStringListModel() model.setStringList(["Item 1", "Item 2", "Item 3", "Item 4"]) # Create the QComboBox and set the model combo_box = QComboBox() combo_box.setModel(model) # Create the main window class MainWindow(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): layout = QVBoxLayout(self) layout.addWidget(combo_box) self.setLayout(layout) self.setWindowTitle('QComboBox with Model') self.setGeometry(300, 300, 300, 200) # Start the application app = QApplication(sys.argv) main_window = MainWindow() main_window.show() sys.exit(app.exec_()) 

This script will create a PyQt5 window with a combo box populated with items from the model. You can replace the list ["Item 1", "Item 2", "Item 3", "Item 4"] with your own data.


More Tags

auto-increment windows-1252 xml-serialization karate rgb sequelize.js bootstrap-selectpicker tensorflow2.x uinavigationbar mobile-webkit

More Programming Guides

Other Guides

More Programming Examples