简体   繁体   English

PyQt5 检查项目是否已经在 QListWidget 中

[英]PyQt5 check if item is already in QListWidget

string = QLineEdit.text()

for i in range(my_lists.count()):
    if string == my_lists.item(i).text():
        print("alrrady exists")
    else:
        my_lists.addItem(string)

It does print already exists but.它确实打印已经存在但是。 If for example I have 4 items in my list widget.例如,如果我的列表小部件中有 4 个项目。 And the input already exists, It will print out "already exists" and add 3 more items which the text's are input.并且输入已经存在,它将打印出“已经存在”并添加另外 3 个输入文本的项目。
(It adds Items based on how many there are but -1) (它根据除了 -1 之外的数量添加项目)
This is probably cause by the for loop so I added break on the if statement.这可能是由 for 循环引起的,所以我在 if 语句中添加了 break。 It adds more items based on how many there are on top of it.它根据其顶部的数量添加更多项目。 So I placed the break to the else statement and you can say that it's better because it only added one.所以我把 break 放在 else 语句中,你可以说它更好,因为它只添加了一个。
(also if you're wondering yes I tried adding break on both of them but it gives me the same result as placing break to the else statment) (另外,如果您想知道是的,我尝试在它们两个上添加 break,但它给我的结果与将 break 放在 else 语句中的结果相同)

This code won't work tho if you have zero items in your list widget so I added如果您的列表小部件中的项目为零,则此代码将不起作用,所以我添加了

if my_lists.count() == 0:
    my_lists.addItem(input)

I tried answering my own question for once, This works but I'm not sure if It's the right way to do it.我试过一次回答我自己的问题,这可行,但我不确定这是否是正确的方法。

input = QLineEdit.text()
books = []


for i in range(QListWidget.count()):
    book = self.bookmarks.item(i).text()
    books.append(book)

if input in books:
    print("Already exists")
else:
    QListWidget.addItem(input)

Because I can't iterate QListWidgets I thought I should move it's content on something I can iterate.因为我无法迭代 QListWidgets,所以我认为我应该将它的内容移动到我可以迭代的东西上。 And from there I started.从那里我开始了。

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

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