【问题标题】:delete items from 3 different lists从 3 个不同的列表中删除项目
【发布时间】:2016-05-09 22:27:14
【问题描述】:

当单击按钮时,我需要一些帮助来同时从某些列表中删除某些项目。

这是代码:

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

当我使用组合键打开QDialog 时,我在QListWidget 中看到了一些项目。在deleteItems 方法中,我从QListWidget 中选择的项目中获取索引和文本。效果很好。

当我按下一个按钮(我已经创建)时,我需要做的是从list_1list_2QListWidget 中删除该项目。

我该怎么做?希望你能帮助我。

【问题讨论】:

    标签: python list pyqt qlistwidget


    【解决方案1】:

    如果你有这个值,那么只需在每个列表中找到它的索引,然后删除它。比如:

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

    也可以直接使用Widow.list_x.remove(value),但是如果值不存在会抛出异常。

    【讨论】:

    • 谢谢你的回答。它适用于 list_2 和 list_1,但不适用于 QlistWidgetQListWidget 填充了 list_2 的项目。那么,当我从 list_2 中删除一个项目时,为什么它没有在 listWidget 中也被删除?
    【解决方案2】:

    Python 列表有一个直接执行该操作的“删除”对象:

    Window.list_2.remove(item_selected)  
    

    (不需要你的 for 循环)

    如果您需要对列表项执行更复杂的操作,可以改为使用index 方法检索项目的索引:

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

    并且在某些情况下,您会想要执行一个 for 循环来获取实际索引,以及列表或其他序列的该索引处的内容。在这种情况下,使用内置的enumerate

    使用枚举模式,(如果remove不存在)看起来像:

    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
    

    【讨论】:

    • 谢谢,enumerate 模式可以满足我的需要 抱歉打扰你了,但是有没有办法刷新QListWidgetQDialog 以在没有我拥有的项目的情况下查看它刚刚删除。我尝试了repaint 方法,但它不起作用。
    • 我建议你再问一个问题——因为它与 Qt 相关,Qt 人可能会想出一个更好的答案。
    猜你喜欢
    • 2021-08-16
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    相关资源
    最近更新 更多