-1

How to remove duplicates from combobox in pyqt4 . i have tried following code but its not removing duplicates from comboBox.

Code:

from PyQt4 import QtCore, QtGui
import sys
app = QtGui.QApplication(sys.argv)
w = QtGui.QWidget()
w.resize(500, 388)

combo=QtGui.QComboBox(w)
combo.setGeometry(QtCore.QRect(150, 50, 251, 31))
combo.addItem("aa")
combo.addItem("bb")
combo.addItem("cc")
combo.addItem("aa")
combo.setDuplicatesEnabled(False)

w.setWindowTitle("PyQt")
w.show()
sys.exit(app.exec_())

2 Answers2

2

It seems you have not read the docs:

This property holds whether the user can enter duplicate items into the combobox.

Note that it is always possible to programmatically insert duplicate items into the combobox.

By default, this property is false (duplicates are not allowed).


the highlight is mine

So a possible solution is to overwrite the addItem method to do the filtering:

from PyQt4 import QtCore, QtGui
import sys


class ComboBox(QtGui.QComboBox):
    def addItem(self, item):
        if item not in self.get_set_items():
            super(ComboBox, self).addItem(item)

    def addItems(self, items):
        items = list(self.get_set_items() | set(items))
        super(ComboBox, self).addItems(items)

    def get_set_items(self):
        return set([self.itemText(i) for i in range(self.count())])


if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    w = QtGui.QWidget()
    w.resize(500, 388)

    combo = ComboBox(w)
    combo.setGeometry(QtCore.QRect(150, 50, 251, 31))
    combo.addItems(["aaa", "bb", "aaa"])
    combo.addItem("aa")
    combo.addItem("bb")
    combo.addItem("cc")
    combo.addItem("aa")
    w.setWindowTitle("PyQt")
    w.show()
    sys.exit(app.exec_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
1

From the qt documentation:

Note that it is always possible to programmatically insert duplicate items into the combobox.

You need to manually avoid duplicates. You could make a set of all the items and then pass its items with addItem.

andreihondrari
  • 5,743
  • 5
  • 30
  • 59