首页 > 解决方案 > 比较对象并在列表中搜索

问题描述

我使用 Python 3 和 PySide2(Qt for Python)(都是最新的)。我有一个 PySide2 对象列表,并且必须检查列表中是否存在某个项目。如果我尝试这样做,我会收到错误消息:

NotImplementedError: operator not implemented.
from PySide2 import QtGui
item = QtGui.QStandardItem()
item1 = QtGui.QStandardItem()

item == item1 # creates error

list1 = [item, item1]
item1 in list1 # creats error

我错了什么?我怎样才能做到这一点?我必须自己实现“==”运算符吗?预先感谢您的帮助!

标签: pythonpython-3.xpyside2

解决方案


如评论中所述,您收到的错误是 PySide 残余的错误的一部分。

我认为你有一个XY 问题,你想要检查是否有一个带有预定义文本的项目。如果是这样,则无需实现运算符==,而是使用findItems()方法:

from PySide2 import QtCore, QtGui

if __name__ == "__main__":
    import sys

    md = QtGui.QStandardItemModel()
    for text in ("Hello", "Stack", "Overflow"):
        md.appendRow(QtGui.QStandardItem(text))

    words = ("Hello", "World")

    for word in words:
        if md.findItems(word, flags=QtCore.Qt.MatchExactly, column=0):
            print(f"{word} exists")
        else:
            print(f"{word} not exists")

或者如果您想搜索其他角色,请使用match()方法:

from PySide2 import QtCore, QtGui

FooRole = QtCore.Qt.UserRole + 1000

if __name__ == "__main__":
    import sys

    md = QtGui.QStandardItemModel()
    for i, text in enumerate(("Hello", "Stack", "Overflow")):
        it = QtGui.QStandardItem(str(i))
        it.setData(text, FooRole)
        md.appendRow(it)

    words = ("Hello", "World")

    for word in words:
        if md.match(
            md.index(0, 0), FooRole, word, hits=1, flags=QtCore.Qt.MatchExactly
        ):
            print(f"{word} exists")
        else:
            print(f"{word} not exists")

推荐阅读