The ModelView Architecture
Qt's MVC-like interface for displaying data in views

ModelViews and Databases course

As you start to build more complex applications with PySide you'll likely come across issues keeping widgets in sync with your data. Data stored in widgets (e.g. a simple QListWidget) is not readily available to manipulate from Python — changes require you to get an item, get the data, and then set it back. The default solution to this is to keep an external data representation in Python, and then either duplicate updates to the both the data and the widget, or simply rewrite the whole widget from the data. This can get ugly quickly, and results in a lot of boilerplate just for fiddling the data.

Thankfully Qt has a solution for this — ModelViews. ModelViews are a powerful alternative to the standard display widgets, which use a regular model interface to interact with data sources — from simple data structures to external databases. This isolates your data, allowing it to be kept in any structure you like, while the view takes care of presentation and updates.

This tutorial introduces the key aspects of Qt's ModelView architecture and uses it to build simple desktop Todo application in PySide.

Model View Controller

Model–View–Controller (MVC) is an architectural pattern used for developing user interfaces which divides an application into three interconnected parts. This separates the internal representation of data from how information is presented to and accepted from the user.

The MVC design pattern decouples three major components —

  • Model holds the data structure which the app is working with.
  • View is any representation of information as shown to the user, whether graphical or tables. Multiple views of the same data model are allowed.
  • Controller accepts input from the user, transforming it into commands to for the model or view.

It Qt land the distinction between the View & Controller gets a little murky. Qt accepts input events from the user (via the OS) and delegates these to the widgets (Controller) to handle. However, widgets also handle presentation of the current state to the user, putting them squarely in the View. Rather than agonize over where to draw the line, in Qt-speak the View and Controller are instead merged together creating a Model/ViewController architecture — called "Model View" for simplicity sake.

Importantly, the distinction between the data and how it is presented is preserved.

The Model View

The Model acts as the interface between the data store and the ViewController. The Model holds the data (or a reference to it) and presents this data through a standardised API which Views then consume and present to the user. Multiple Views can share the same data, presenting it in completely different ways.

You can use any "data store" for your model, including for example a standard Python list or dictionary, or a database (via e.g. SQLAlchemy) — it's entirely up to you.

The two parts are essentially responsible for —

  1. The model stores the data, or a reference to it and returns individual or ranges of records, and associated metadata or display instructions.
  2. The view requests data from the model and displays what is returned on the widget.

There is an in-depth discussion of the Qt architecture in the documentation.

Create GUI Applications with Python & Qt5
The easy way to create desktop applications

The complete guide to building GUI applications with PySide2. From the basics of creating a desktop window to the key features you need to build real apps.

Downloadable ebook (PDF, ePub) & Complete Source code

To support developers in [[ countryRegion ]] I give a [[ localizedDiscount[couponCode] ]]% discount with the code [[ couponCode ]] — Enjoy!

For [[ activeDiscount.description ]] I'm giving a [[ activeDiscount.discount ]]% discount with the code [[ couponCode ]] — Enjoy!

A simple Model View — a Todo List

To demonstrate how to use the ModelViews in practise, we'll put together a very simple implementation of a desktop Todo List. This will consist of a QListView for the list of items, a QLineEdit to enter new items, and a set of buttons to add, delete, or mark items as done.

The UI

The simple UI was laid out using Qt Creator and saved as mainwindow.ui. The .ui file and all the other parts can be downloaded below.

Todo application Source Code

Designing a Simple Todo app in Qt Creator Designing a Simple Todo app in Qt Creator

The running app is shown below.

The running Todo GUI (nothing works yet) The running Todo GUI (nothing works yet)

The widgets available in the interface were given the IDs shown in the table below.

objectName Type Description
todoView QListView The list of current todos
todoEdit QLineEdit The text input for creating a new todo item
addButton QPushButton Create the new todo, adding it to the todos list
deleteButton QPushButton Delete the current selected todo, removing it from the todos list
completeButton QPushButton Mark the current selected todo as done

We'll use these identifiers to hook up the application logic later.

The Model

We define our custom model by subclassing from a base implementation, allowing us to focus on the parts unique to our model. Qt provides a number of different model bases, including lists, trees and tables (ideal for spreadsheets).

For this example we are displaying the result to a QListView. The matching base model for this is QAbstractListModel. The outline definition for our model is shown below.

python
class TodoModel(QtCore.QAbstractListModel):
    def __init__(self, *args, todos=None, **kwargs):
        super(TodoModel, self).__init__(*args, **kwargs)
        self.todos = todos or []

    def data(self, index, role):
        if role == Qt.DisplayRole:
            # See below for the data structure.
            status, text = self.todos[index.row()]
            # Return the todo text only.
            return text

    def rowCount(self, index):
        return len(self.todos)

The.todos variable is our data store and the two methods rowcount() and data() are standard Model methods we must implement for a list model. We'll go through these in turn below.

.todos list

The data store for our model is .todos, a simple Python list in which we'll store a tuple of values in the format [(bool, str), (bool, str), (bool, str)] where bool is the done state of a given entry, and str is the text of the todo.

We initialise self.todo to an empty list on startup, unless a list is passed in via the todos keyword argument.

self.todos = todos or [] will set self.todos to the provided todos value if it is truthy (i.e. anything other than an empty list, the boolean False or None the default value), otherwise it will be set to the empty list [].

To create an instance of this model we can simply do —

python
model = TodoModel()   # create an empty todo list

Or to pass in an existing list —

python
todos = [(False, 'an item'), (False, 'another item')]
model = TodoModel(todos)

.rowcount()

The .rowcount() method is called by the view to get the number of rows in the current data. This is required for the view to know the maximum index it can request from the data store (row count-1). Since we're using a Python list as our data store, the return value for this is simply the len() of the list.

.data()

This is the core of your model, which handles requests for data from the view and returns the appropriate result. It receives two parameters index and role.

index is the position/coordinates of the data which the view is requesting, accessible by two methods .row() and .column() which give the position in each dimension.

For our QListView the column is always 0 and can be ignored, but you would need to use this for 2D data in a spreadsheet view.

role is a flag indicating the type of data the view is requesting. This is because the .data() method actually has more responsibility than just the core data. It also handles requests for style information, tooltips, status bars, etc. — basically anything that could be informed by the data itself.

The naming of Qt.DisplayRole is a bit weird, but this indicates that the view is asking us "please give me data for display". There are other roles which the data can receive for styling requests or requesting data in "edit-ready" format.

Role Value Description
Qt.DisplayRole 0 The key data to be rendered in the form of text. (QString)
Qt.DecorationRole 1 The data to be rendered as a decoration in the form of an icon. (QColor, QIcon or QPixmap)
Qt.EditRole 2 The data in a form suitable for editing in an editor. (QString)
Qt.ToolTipRole 3 The data displayed in the item's tooltip. (QString)
Qt.StatusTipRole 4 The data displayed in the status bar. (QString)
Qt.WhatsThisRole 5 The data displayed for the item in "What's This?" mode. (QString)
Qt.SizeHintRole 13 The size hint for the item that will be supplied to views. (QSize)

For a full list of available roles that you can receive see the Qt ItemDataRole documentation. Our todo list will only be using Qt.DisplayRole and Qt.DecorationRole.

Basic implementation

Below is the basic stub application needed to load the UI and display it. We'll add our model code and application logic to this base.

python
import sys

from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtCore import Qt

from MainWindow import Ui_MainWindow


class TodoModel(QtCore.QAbstractListModel):
    def __init__(self, todos=None):
        super().__init__()
        self.todos = todos or []

    def data(self, index, role):
        if role == Qt.DisplayRole:
            status, text = self.todos[index.row()]
            return text

    def rowCount(self, index):
        return len(self.todos)


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.model = TodoModel()
        self.todoView.setModel(self.model)


app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

We define our TodoModel as before, and initialise the MainWindow object. In the __init__ for the MainWindow we create an instance of our todo model and set this model on the todo_view. Save this file as todo.py and run it with —

bash
python3 todo.py

While there isn't much to see yet, the QListView and our model are actually working — if you add some default data you'll see it appear in the list.

python
self.model = TodoModel(todos=[(False, 'my first todo')])

QListView showing hard-coded todo item QListView showing hard-coded todo item

You can keep adding items manually like this and they will show up in order in the QListView. Next we'll make it possible to add items from within the application.

First create a new method on the MainWindow named add. This is our callback which will take care of adding the current text from the input as a new todo. Connect this method to the addButton.pressed signal at the end of the __init__ block.

python
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.model = TodoModel()
        self.todoView.setModel(self.model)
        # Connect the button.
            self.addButton.pressed.connect(self.add)

    def add(self):
        """
        Add an item to our todo list, getting the text from the QLineEdit .todoEdit
        and then clearing it.
        """
        text = self.todoEdit.text()
        if text: # Don't add empty strings.
            # Access the list via the model.
            self.model.todos.append((False, text))
            # Trigger refresh.
            self.model.layoutChanged.emit()
            # Empty the input
            self.todoEdit.setText("")

In the add block notice the line self.model.layoutChanged.emit(). Here we're emitting a model signal .layoutChanged to let the view know that the shape of the data has been altered. This triggers a refresh of the entirety of the view. If you omit this line, the todo will still be added but the QListView won't update.

If just the data is altered, but the number of rows/columns are unaffected you can use the .dataChanged() signal instead. This also defines an altered region in the data using a top-left and bottom-right location to avoid redrawing the entire view.

Hooking up the other actions

We can now connect the rest of the button's signals and add helper functions for performing the delete and complete operations. We add the button signals to the __init__ block as before.

python
        self.addButton.pressed.connect(self.add)
        self.deleteButton.pressed.connect(self.delete)
        self.completeButton.pressed.connect(self.complete)

Then define a new delete method as follows —

python
    def delete(self):
        indexes = self.todoView.selectedIndexes()
        if indexes:
            # Indexes is a list of a single item in single-select mode.
            index = indexes[0]
            # Remove the item and refresh.
            del self.model.todos[index.row()]
            self.model.layoutChanged.emit()
            # Clear the selection (as it is no longer valid).
            self.todoView.clearSelection()

We use self.todoView.selectedIndexes to get the indexes (actually a list of a single item, as we're in single-selection mode) and then use the .row() as an index into our list of todos on our model. We delete the indexed item using Python's del operator, and then trigger a layoutChanged signal because the shape of the data has been modified.

Finally, we clear the active selection since the item it relates to may now out of bounds (if you had selected the last item).

You could try make this smarter, and select the last item in the list instead

The complete method looks like this —

python

    def complete(self):
        indexes = self.todoView.selectedIndexes()
        if indexes:
            index = indexes[0]
            row = index.row()
            status, text = self.model.todos[row]
            self.model.todos[row] = (True, text)
            # .dataChanged takes top-left and bottom right, which are equal
            # for a single selection.
            self.model.dataChanged.emit(index, index)
            # Clear the selection (as it is no longer valid).
            self.todoView.clearSelection()

This uses the same indexing as for delete, but this time we fetch the item from the model .todos list and then replace the status with True.

We have to do this fetch-and-replace, as our data is stored as Python tuples which cannot be modified.

The key difference here vs. standard Qt widgets is that we make changes directly to our data, and simply need to notify Qt that some change has occurred — updating the widget state is handled automatically.

Using Qt.DecorationRole

If you run the application now you should find that adding and deleting both work, but while completing items is working, there is no indication of it in the view. We need to update our model to provide the view with an indicator to display when an item is complete. The updated model is shown below.

python
tick = QtGui.QImage('tick.png')


class TodoModel(QtCore.QAbstractListModel):
    def __init__(self, *args, todos=None, **kwargs):
        super(TodoModel, self).__init__(*args, **kwargs)
        self.todos = todos or []

    def data(self, index, role):
        if role == Qt.DisplayRole:
            _, text = self.todos[index.row()]
            return text

        if role == Qt.DecorationRole:
            status, _ = self.todos[index.row()]
            if status:
                return tick

    def rowCount(self, index):
        return len(self.todos)

We're using a tick icon tick.png to indicate completed items, which we load into a QImage object named tick. In the model we've implemented a handler for the Qt.DecorationRole which returns the tick icon for rows who's status is True (for complete).

The icon I'm using is taken from the Fugue set by p.yusukekamiyamane

Instead of an icon you can also return a color, e.g. QtGui.QColor('green') which will be drawn as solid square.

Running the app you should now be able to mark items as complete.

Todos Marked Complete Todos Marked Complete

A persistent data store

Our todo app works nicely, but it has one fatal flaw — it forgets your todos as soon as you close the application While thinking you have nothing to do when you do may help to contribute to short-term feelings of Zen, long term it's probably a bad idea.

The solution is to implement some sort of persistent data store. The simplest approach is a simple file store, where we load items from a JSON or Pickle file at startup, and write back on changes.

To do this we define two new methods on our MainWindow class — load and save. These load data from a JSON file name data.json (if it exists, ignoring the error if it doesn't) to self.model.todos and write the current self.model.todos out to the same file, respectively.

python
    def load(self):
        try:
            with open('data.json', 'r') as f:
                self.model.todos = json.load(f)
        except Exception:
            pass

    def save(self):
        with open('data.json', 'w') as f:
            data = json.dump(self.model.todos, f)

To persist the changes to the data we need to add the .save() handler to the end of any method that modifies the data, and the .load() handler to the __init__ block after the model has been created.

The final code looks like this —

python
import json
import sys

from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtCore import Qt

from MainWindow import Ui_MainWindow

tick = QtGui.QImage("tick.png")


class TodoModel(QtCore.QAbstractListModel):
    def __init__(self, todos=None):
        super().__init__()
        self.todos = todos or []

    def data(self, index, role):
        if role == Qt.DisplayRole:
            _, text = self.todos[index.row()]
            return text

        if role == Qt.DecorationRole:
            status, _ = self.todos[index.row()]
            if status:
                return tick

    def rowCount(self, index):
        return len(self.todos)


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()

        self.setupUi(self)
        self.model = TodoModel()
        self.load()
        self.todoView.setModel(self.model)
        self.addButton.pressed.connect(self.add)
        self.deleteButton.pressed.connect(self.delete)
        self.completeButton.pressed.connect(self.complete)

    def add(self):
        """
        Add an item to our todo list, getting the text from the QLineEdit .todoEdit
        and then clearing it.
        """
        text = self.todoEdit.text()
        if text:  # Don't add empty strings.
            # Access the list via the model.
            self.model.todos.append((False, text))
            # Trigger refresh.
            self.model.layoutChanged.emit()
            # Empty the input
            self.todoEdit.setText("")
            self.save()

    def delete(self):
        indexes = self.todoView.selectedIndexes()
        if indexes:
            # Indexes is a list of a single item in single-select mode.
            index = indexes[0]
            # Remove the item and refresh.
            del self.model.todos[index.row()]
            self.model.layoutChanged.emit()
            # Clear the selection (as it is no longer valid).
            self.todoView.clearSelection()
            self.save()

    def complete(self):
        indexes = self.todoView.selectedIndexes()
        if indexes:
            index = indexes[0]
            row = index.row()
            status, text = self.model.todos[row]
            self.model.todos[row] = (True, text)
            # .dataChanged takes top-left and bottom right, which are equal
            # for a single selection.
            self.model.dataChanged.emit(index, index)
            # Clear the selection (as it is no longer valid).
            self.todoView.clearSelection()
            self.save()

    def load(self):
        try:
            with open("data.json", "r") as f:
                self.model.todos = json.load(f)
        except Exception:
            pass

    def save(self):
        with open("data.json", "w") as f:
            data = json.dump(self.model.todos, f)


app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()


If the data in your application has the potential to get large or more complex, you may prefer to use an actual database to store it. In this case the model will wrap the interface to the database and query it directly for data to display. I'll cover how to do this in an upcoming tutorial.

For another interesting example of a QListView see this example media player application. It uses the Qt built-in QMediaPlaylist as the datastore, with the contents displayed to a QListView.

Complete Mark As Complete Next

Continue reading

QComboBox  pyside

The QComboBox is a simple widget for presenting a list of options to your users in PyQt, taking up the minimum amount of screen space. The widget can have a single selected item, which is displayed in the widget area. When selected a QComboBox pops out a list of possible values from which you can select. A QComboBox can also - optionally - be made editable, so your users can enter their own values onto the list of possible values. QComboBox in its closed and open state Populating a QComboBox Items can be added or inserted to a QComboBox, where adding appends the item to the end of the current list, while insert inserts them in a specific index in the existing list. There are convenience methods for adding multiple items to a combobox and also for adding icons to the list. The following example will demonstrate each of these using a series of comboboxes. python from PyQt5.QtWidgets import QComboBox, QMainWindow, QApplication, QWidget, QVBoxLayout from PyQt5.QtGui import QIcon import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() combobox1 = QComboBox() combobox1.addItem('One') combobox1.addItem('Two') combobox1.addItem('Three') combobox1.addItem('Four') combobox2 = QComboBox() combobox2.addItems(['One', 'Two', 'Three', 'Four']) combobox3 = QComboBox() combobox3.addItems(['One', 'Two', 'Three', 'Four']) combobox3.insertItem(2, 'Hello!') combobox4 = QComboBox() combobox4.addItems(['One', 'Two', 'Three', 'Four']) combobox4.insertItems(2, ['Hello!', 'again']) combobox5 = QComboBox() icon_penguin = QIcon('animal-penguin.png') icon_monkey = QIcon('animal-monkey.png') icon_bauble = QIcon('bauble.png') combobox5.addItem(icon_penguin, 'Linux') combobox5.addItem(icon_monkey, 'Monkeyix') combobox5.insertItem(1, icon_bauble, 'Baublix') layout = QVBoxLayout() layout.addWidget(combobox1) layout.addWidget(combobox2) layout.addWidget(combobox3) layout.addWidget(combobox4) layout.addWidget(combobox5) container = QWidget() container.setLayout(layout) self.setCentralWidget(container) def current_text_changed(self, s): print("Current text: ", s) app = QApplication(sys.argv) w = MainWindow() w.show() app.exec_() Run the example and compare the result with each series of add and insert steps. Adding items to a QComboBox You can replace the text at a specific index in the list by calling .setItemText() for example. python widget.setItemText(3, 'new text') Finally, you can clear a QComboBox -- removing all items in it -- by calling .clear(). python widget.clear() QComboBox signals The QComboBox emits a number of signals on state changes. When the currently selected item changes, the widget emits .currentIndexChanged() and .currentTextChanged() signals. The first receives the index of the selected entry while the second receives the text of that item. There is a further signal .activated() which is emitted for user-selections whether the index is changed or not: selecting the same entry again will still emit the signal. Highlighting an entry in the QComboBox popup list will emit the .highlighted() signal. The following example demonstrates these signals in action. python from PyQt5.QtWidgets import QComboBox, QMainWindow, QApplication import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() combobox = QComboBox() combobox.addItems(['One', 'Two', 'Three', 'Four']) # Connect signals to the methods. combobox.activated.connect(self.activated) combobox.currentTextChanged.connect(self.text_changed) combobox.currentIndexChanged.connect(self.index_changed) self.setCentralWidget(combobox) def activated(Self, index): print("Activated index:", index) def text_changed(self, s): print("Text changed:", s) def index_changed(self, index): print("Index changed", index) app = QApplication(sys.argv) w = MainWindow() w.show() app.exec_() If you run the example the signals emitted as you interact with the QComboBox will be shown in the console, giving output like that shown below. Note that when re-selecting the same entry, only the .activated() signal is emitted. python Index changed 1 Text changed: Two Activated index: 1 Index changed 2 Text changed: Three Activated index: 2 Index changed 3 Text changed: Four Activated index: 3 Activated index: 3 Activated index: 3 Getting the current state In addition to the signals, QComboBox has a few methods for getting the current state at any time. For example, you can use .currentIndex() to get the index of the currently selected item in the combobox, or use .currentText() to get the text. With the index you can also look up the text of a specific item using .itemText(). Finally, you can use .count() to get the total number of items in the combobox list. In the example below, we use the activated signal we've already seen to hook up a number of methods which get information about the combobox and display this in the console. As you select any item in the combobox every method will run printing a message to the console. python from PyQt5.QtWidgets import QComboBox, QMainWindow, QApplication import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() # Keep a reference to combobox on self, so we can access it in our methods. self.combobox = QComboBox() self.combobox.addItems(['One', 'Two', 'Three', 'Four']) # Connect signal to our methods. self.combobox.activated.connect(self.check_index) self.combobox.activated.connect(self.current_text) self.combobox.activated.connect(self.current_text_via_index) self.combobox.activated.connect(self.current_count) self.setCentralWidget(self.combobox) def check_index(self, index): cindex = self.combobox.currentIndex() print(f"Index signal: {index}, currentIndex {cindex}") def current_text(self, _): # We receive the index, but don't use it. ctext = self.combobox.currentText() print("Current text", ctext) def current_text_via_index(self, index): ctext = self.combobox.itemText(index) # Get the text at index. print("Current itemText", ctext) def current_count(self, index): count = self.combobox.count() print(f"Index {index+1}/{count}") app = QApplication(sys.argv) w = MainWindow() w.show() app.exec_() Running this and selecting different items in the combobox will show the outputs. python Current text Two Current itemText Two Index 1/4 Index signal: 2, currentIndex 2 Current text Three Current itemText Three Index 2/4 Index signal: 3, currentIndex 3 Current text Four Current itemText Four Index 3/4 Editable comboboxes You can set a QComboBox to be editable allowing the user to type enter the values not currently in the list. Entered values can be added to the list, or just used as a value which is not inserted. To enable editing you can call .setEditable(True) on the widget, while control of how inserts operate is handled through the insert policy. This is set by calling .setInsertPolicy() passing one of the following flags: Flag Value Behavior QComboBox.NoInsert 0 No insert QComboBox.InsertAtTop 1 Insert as first item QComboBox.InsertAtCurrent 2 Replace currently selected item QComboBox.InsertAtBottom 3 Insert after last item QComboBox.InsertAfterCurrent 4 Insert after current item QComboBox.InsertBeforeCurrent 5 Insert before current item QComboBox.InsertAlphabetically 6 Insert in alphabetical order For PyQt6 use the fully-qualified flag name, i.e. QComboBox.InsertPolicy.NoInsert For example, to insert new values alphabetically, you would use. python widget.setInsertPolicy(QComboBox.InsertAlphabetically) If the combobox is set to be editable, but QComboBox.NoInsert is set as the insert policy, users will be able to enter their own custom values, but they will not be added to the list. In the following example we have two QComboBox widgets: one which is our editable box and the second which controls the insert policy of the first. Note that since the values of the flags (see above) are just numbers from 0 to 6, we can use the index to determine the flag. python from PyQt5.QtWidgets import QComboBox, QMainWindow, QApplication, QWidget, QVBoxLayout import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() # Keep a reference to combobox on self, so we can access it in our methods. self.combobox = QComboBox() self.combobox.addItems(['One', 'Two', 'Three', 'Four']) self.combobox.setEditable(True) self.combobox.currentTextChanged.connect(self.current_text_changed) # Insert policies self.insertpolicy = QComboBox() self.insertpolicy.addItems([ 'NoInsert', 'InsertAtTop', 'InsertAtCurrent', 'InsertAtBottom', 'InsertAfterCurrent', 'InsertBeforeCUrrent', 'InsertAlphabetically' ]) # The index in the insertpolicy combobox (0-6) is the correct flag value to set # to enable that insert policy. self.insertpolicy.currentIndexChanged.connect(self.combobox.setInsertPolicy) layout = QVBoxLayout() layout.addWidget(self.combobox) layout.addWidget(self.insertpolicy) container = QWidget() container.setLayout(layout) self.setCentralWidget(container) def current_text_changed(self, s): print("Current text: ", s) app = QApplication(sys.argv) w = MainWindow() w.show() app.exec_() If you run this example you'll notice you can now type into the (top) editable combobox and submit them by pressing Enter. The .currentTextChanged() signal will be emitted as you type into the field. python Current text: w Current text: wq Current text: wqe Current text: wqew Current text: wqeww Current text: wqewwq Current text: wqewwqe By default the insert policy is set to QComboBox.NoInsert so entered values will not be added, just set as the value of the combobox. By selecting the insert policy in the second combobox you can change this behavior, having new entries added to the list. Editing a QComboBox with insert policy When you allow users to add values to the list, you may wish to constrain the maximum number of entries. This can be done using .setMaxCount, e.g. python widget.setMaxCount(10) More