【问题标题】:How to move multiple lines at once up or down in PyQt List Widget?如何在 PyQt List Widget 中一次向上或向下移动多行?
【发布时间】:2021-08-31 07:29:06
【问题描述】:

我正在使用以下代码在 PyQt6 列表小部件中向上移动单个项目

def move_item_up_in_list_box(self):
    row = self.listWidget.currentRow()
    text = self.listWidget.currentItem().text()
    self.listWidget.insertItem(row-1, text)
    self.listWidget.takeItem(row+1)
    self.listWidget.setCurrentRow(row-1)

But I couldn't find an option to get the index positions when multiple lines are selected, though 'self.listWidget.selectedItems()' 返回所选项目中的文本,我不知道如何向上或向下移动多行。

【问题讨论】:

  • selectedItems() 不返回“文本”。它返回所选项目的列表。
  • 是的,我只是遍历列表并使用 .text() 来获取文本,如何获取所选项目的索引位置?

标签: python pyqt5 qlistwidget pyqt6


【解决方案1】:

只需循环遍历selectedItems() 并使用row() 获取每个行。

    for item in self.listWidget.selectedItems():
        row = self.listWidget.row(item)
        # ...

考虑到选择模型通常会保持已选择项目的顺序,因此您应该始终在移动项目之前重新排序项目,并记住如果您将项目向下移动,它们应该以反向移动 em> 订购。

    def move_items(self, down=False):
        items = []
        for item in self.listWidget.selectedItems():
            items.append((self.listWidget.row(item), item))
        items.sort(reverse=down)
        delta = 1 if down else -1
        for row, item in items:
            self.listWidget.takeItem(row)
            self.listWidget.insertItem(row + delta, item)

【讨论】:

  • 感谢您提供的详细信息,选择顺序、排序、反转列表以向下移动所有这些都经过了巧妙的思考!
  • @JackZero 不客气!请记住,如果答案解决了您的问题,您应该通过单击其左侧的灰色刻度标记将其标记为已接受。 (顺便说一句,我修复了对列表小部件的错误引用,因为我在粘贴代码时忘记将 w 替换为 self.listWidget
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 1970-01-01
  • 2015-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多