简体   繁体   中英

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. And the input already exists, It will print out "already exists" and add 3 more items which the text's are input.
(It adds Items based on how many there are but -1)
This is probably cause by the for loop so I added break on the if statement. 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.
(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)

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. And from there I started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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