0

I am using the following code to move a single item up in the PyQt6 list widget

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()' returns the texts in the selected items, I couldn't figure out how to move multiple lines up or down.

musicamante
  • 41,230
  • 6
  • 33
  • 58
Jack Zero
  • 77
  • 6

1 Answers1

0

Just cycle through the selectedItems() and use row() to get the row of each one.

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

Consider that the selection model usually keeps the order in which items have been selected, so you should always reorder the items before moving them, and remember that if you move items down, they should be moved in reverse order.

    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)
musicamante
  • 41,230
  • 6
  • 33
  • 58
  • Thanks for the precise details, the selection order, sorting, reversing the the list for moving down all were brilliantly thought through! – Jack Zero Jun 15 '21 at 20:12
  • @JackZero You're welcome! Remember that if an answer solves your issue, you should mark it as accepted by clicking on the gray tick mark on its left. (Btw, I fixed a wrong reference to the list widget, as I forgot to replace `w` with `self.listWidget` when I pasted the code back) – musicamante Jun 15 '21 at 20:34