简体   繁体   中英

delete items from 3 different lists

I need some help with deleting some items from some lists at the same time, when a button is clicked.

This is the code:

class Window(QMainWindow):
  list_1 = []  #The items are strings
  list_2 = []  #The items are strings

  def __init__(self):
    #A lot of stuff in here

  def fillLists(self):
    #I fill the lists list_1 and list_2 with this method

  def callAnotherClass(self):
    self.AnotherClass().exec_()   #I do this to open a QDialog in a new window

class AnotherClass(QDialog):
  def __init__(self):
    QDialog.__init__(self)

    self.listWidget = QListWidget()

  def fillListWidget(self):
    #I fill self.listWidget in here

  def deleteItems(self):
    item_index = self.listWidget.currentRow()
    item_selected = self.listWidget.currentItem().text()
    for i in Window.list_2:
      if i == item_selected:
        ?????????? #Here is where i get confussed

When i open the QDialog with a combination of keys, i see in the QListWidget some items. In the deleteItems method, i get the index and the text from the item that i selected in the QListWidget . That works fine.

What i need to do is to delete the item from the list_1 , list_2 , and the QListWidget when i press a button (that i have already created).

How can i do this? Hope you can help me.

if you have the value, then just find its index in each list and then delete it. Something like:

 item_selected = self.listWidget.currentItem().text()
 i = Window.list_2.index(item_selected)
 if i >= 0: 
    del Window.list_2[i]

You can also use directly Widow.list_x.remove(value) but it can throw an exception if the value does not exist.

Python lists have a "remove" object that perform that action directly:

Window.list_2.remove(item_selected)  

(with no need for your for loop)

If you ever need to perform more complex operations on the list items, you can retrieve an item's index with the index method instead:

position = Window.list_2.index(item_selected)
Window.list_2[position] += "(selected)"

And in some ocasions you will want to do a for loop getting to the actual index, as well as the content at that index of a list or other sequence. In that case, use the builtin enumerate .

Using the enumerate pattern, (if remove did not exist) would look like:

for index, content in enumerate(Window.list_2):
  if content == item_selected:
      del Window.list_2[index]
      # must break out of the for loop,
      # as the original list now has changed: 
      break

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