Zuckonit
Zuckonit

Reputation: 685

how to sort the items in QListWidget by drop and drag

I am newer to pyqt, I am using it to write some GUI, could anybody please tell me how to sort the items in QListWidget by drop and drag?

thanks in advance

Upvotes: 0

Views: 6141

Answers (1)

Gary Hughes
Gary Hughes

Reputation: 4510

QListWidget inherits from QAbstractItemView. You can use the QAbstractItemView.setDragDropMode() and set it to QAbstractItemView.InternalMove if you'd like to be able to change the order of your items with drag & drop.

Here's the relevent section of the documentation.

Here's a quick example showing it in action:

import sys
from PyQt4.QtGui import QApplication, QWidget, \
    QVBoxLayout, QListWidget, QAbstractItemView

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.widget_layout = QVBoxLayout()

        # Create ListWidget and add 10 items to move around.
        self.list_widget = QListWidget()
        for x in range(1, 11):
            self.list_widget.addItem('Item {:02d}'.format(x))

        # Enable drag & drop ordering of items.
        self.list_widget.setDragDropMode(QAbstractItemView.InternalMove)

        self.widget_layout.addWidget(self.list_widget)
        self.setLayout(self.widget_layout)


if __name__ == '__main__':
  app = QApplication(sys.argv)
  widget = Widget()
  widget.show()

  sys.exit(app.exec_())  

Upvotes: 5

Related Questions