Search code examples
pythonpyqt5qlistwidgetpyqt6

How to move multiple lines at once up or down in PyQt List Widget?


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.


Solution

  • 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)