python - 比较对象并在列表中搜索
问题描述
我使用 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
我错了什么?我怎样才能做到这一点?我必须自己实现“==”运算符吗?预先感谢您的帮助!
解决方案
如评论中所述,您收到的错误是 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")
推荐阅读
- java - 无法使用 VSCode 运行/编译 java 程序
- javascript - 获取彼此最接近的两个单词之间的字符串
- python - Roc 曲线未显示在图表上 (Sklearn-kNN)
- python-3.x - 从 python bytes-str 生成 4 字节校验和
- ruby-on-rails - Rails + Carrierwave + MiniMagick:如何保存 gif 动画?
- c# - 作为集成测试的一部分,为已安装的 ExcelDna 插件调用 Excel 功能区按钮
- html - 使用 powershell 下载文件
- jquery - jquery 不能从外部 symfony 包中工作
- django - 在pycharm中创建django项目时出错
- r - 在 purrr 中使用 MASS::stepAIC