SearchableComboBox

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class SearchableComboBox(QComboBox):
    """
    From
    https://stackoverflow.com/questions/4827207/how-do-i-filter-the-pyqt-qcombobox-items-based-on-the-text-input
    """
    def __init__(self, parent=None):
        super(SearchableComboBox, self).__init__(parent)
        self.setFocusPolicy(Qt.StrongFocus)
        self.setEditable(True)
        self.setInsertPolicy(QComboBox.NoInsert)
        self.completer = QCompleter(self)
        # always show all completions
        self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.__filterModel = QSortFilterProxyModel(self)
        self.__filterModel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setPopup(self.view())
        self.setCompleter(self.completer)
        self.lineEdit().textEdited[unicode].connect(self.__filterModel.setFilterFixedString)
        self.completer.activated.connect(self.setTextIfCompleterIsClicked)

        self.__filterModel.setSourceModel(self.model())
        self.completer.setModel(self.__filterModel)

    def clear(self):
        self.model().clear()

    def addItem(self, item):
        self.model().appendRow(QStandardItem(item))

    def addItems(self, items):
        for item in items:
            self.model().appendRow(QStandardItem(item))

    def setModel(self, model):
        super(SearchableComboBox, self).setModel(model)
        self.__filterModel.setSourceModel(model)
        self.completer.setModel(self.__filterModel)

    def setModelColumn(self, column):
        self.completer.setCompletionColumn(column)
        self.__filterModel.setFilterKeyColumn(column)
        super(SearchableComboBox, self).setModelColumn(column)

    def view(self):
        return self.completer.popup()

    def index(self):
        return self.currentIndex()

    def setTextIfCompleterIsClicked(self, text):
        if text:
            index = self.findText(text)
            self.setCurrentIndex(index)

Leave a Reply

Your email address will not be published. Required fields are marked *