比较对象并在列表中搜索 [英] Compare objects and search in list
问题描述
我使用 Python 3 和 PySide2(Qt for Python)(都是最新的).我有一个 PySide2 对象列表,必须检查列表中是否存在一个项目.如果我尝试这样做,我会收到错误:
I use Python 3 and PySide2 (Qt for Python) (both up to date). I have a list of PySide2 objects and have to check if an item exists in the list. If I try to do this, I get the error:
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
我做错了什么?我怎样才能做到这一点?我必须自己实现=="运算符吗?预先感谢您的帮助!
What do I wrong? How can I do this? Do I have to implement the "==" operator myself? Thank you in advance for your help!
推荐答案
如评论中所述,您得到的错误是 bug 是 PySide 的残余.
As noted in a comment, the error you get is part of a bug that is remnants of PySide.
我认为您有一个 XY 问题,您想要检查是否有带有预定义文本.如果是这样,则不需要实现运算符 ==
而是使用 findItems() 方法:
I think that you have an XY problem, and what you want is to check if there is an item with a predefined text. If so, it is not necessary to implement the operator ==
but use the findItems() method:
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() 方法搜索其他角色:
Or use the match() method if you want to search for some other role:
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")
这篇关于比较对象并在列表中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!