简体   繁体   English

如何从pyqt4 python中的QcomboBox中删除重复项

[英]How to remove duplicates from QcomboBox in pyqt4 python

How to remove duplicates from combobox in pyqt4 .如何从 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_())

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).默认情况下,此属性为 false(不允许重复)。


the highlight is mine亮点是我的

So a possible solution is to overwrite the addItem method to do the filtering:所以一个可能的解决方案是覆盖 addItem 方法来进行过滤:

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_())

From the qt documentation :qt 文档

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 .您可以制作一set所有项目,然后使用addItem传递其项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM