'QComboBox - narrow selection when typing more than one letter

I have a combobox

c = QCombobox(self)
c.addItem("001")
c.addItem("002")
c.addItem("003")
c.addItem("004")
c.addItem("010")
c.addItem("011")
c.addItem("012")

Is it possible, when user clicks the combobox c and the list is expanded and when he starts typing e.g. the sequence 011 to automatically select the item "011"? In a default state only the first number (letter) works to help to narrow the selection.

This code (suggested by V.K. author of HiFile) does not work.

c = qtw.QComboBox(self)
for key, value in self.c_dict.items():
    c.addItem(key)

c.setEditable(True)
completer = c.completer()
completer.setFilterMode(QtCore.Qt.MatchStartsWith)
completer.setCompletionMode(qtw.QCompleter.PopupCompletion)


Solution 1:[1]

Get a QCompleter object from your combo box using QComboBox::completer() and then set filter mode using QCompleter::setFilterMode(filterMode) where filterMode should be either Qt::MatchContains or Qt::MatchStartsWith, depending or your needs. You may also need to set QCompleter::setCompletionMode(QCompleter::PopupCompletion)... In simple cases everything should work out-of-the box after setting these. In more complex cases, there are lots of completer customizations possible, but be prepared that it is not easy and it does not have intuitive API. Combo boxes and completers are among the beginner-not-so-friendly parts of Qt.

Here is the minimalistic example which works for me. It is in C++ but you can certainly translate it to Python.

#include <QApplication>
#include <QComboBox>
#include <QCompleter>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QComboBox w;
    w.setEditable(true);
    w.addItems({"10", "01", "11"});
    w.setCurrentText(QString());
    w.setInsertPolicy(QComboBox::NoInsert);
    w.completer()->setCompletionMode(QCompleter::PopupCompletion);
    w.show();
    return a.exec();
}

Actually I found that I do not need to set filter mode, because filter mode "StartsWith" is the default. But I needed to set the completion mode to popup. Also notice that I am not creating a competer, I am using the one which was created by Qt automatically in the combo box.

And it is also a good thing to change the insert policy, because the default value "insert at bottom" is just plain nonsense, which was left in Qt probably only for backward compatibility... (as I said above, combo box and completer API is a mess).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1