Brett La Pierre
Brett La Pierre

Reputation: 533

PyQT5 drag and drop with internal move between two QListWidgets

I'm looking for drag/drop functionality from list 1 into list 2 and I also want drag/drop functionality for the items internally in list 2. I cannot find a built in method to do both of these as requested. Thank you.

enter image description here

Here is my code. Thank you!

import sys
from PyQt5.QtWidgets import *


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        hbox = QHBoxLayout(self)

        self.listWidget1 = QListWidget(self)
        self.listWidget1.addItems(['red', 'green', 'blue'])
        self.listWidget1.setDragDropMode(QAbstractItemView.DragDrop)

        self.listWidget2 = QListWidget(self)
        self.listWidget2.addItems(['black', 'silver', 'grey'])
        self.listWidget2.setDragDropMode(QAbstractItemView.InternalMove)
        self.listWidget2.setAcceptDrops(True)

        hbox.addWidget(self.listWidget1)
        hbox.addWidget(self.listWidget2)

        self.setLayout(hbox)
        self.setGeometry(300, 300, 350, 250)
        self.show()


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

Upvotes: 0

Views: 623

Answers (1)

alec
alec

Reputation: 6122

You could change the DragDropMode depending on the source of the event.

class List(QListWidget):

    def dragEnterEvent(self, event):
        if event.source() is self:
            self.setDragDropMode(QAbstractItemView.InternalMove)
        else:
            self.setDragDropMode(QAbstractItemView.DragDrop)
        super().dragEnterEvent(event)

And use the subclass instead:

self.listWidget2 = List(self)

Upvotes: 1

Related Questions