Thursday 11 February 2021

PyQt5 Drag and Drop QGroupBox

 Custom QGroupBox for drag-and-drop in Python PyQt5.

I prefer this over the "file open" dialog, as it's much faster. And the user probably already has the window open that they are working with, so there is no need to navigate to it again.

It looks like this (with some CSS):




The code:

class QGroupBoxDrop(QGroupBox):

def __init__(self):
super().__init__()
self.setAcceptDrops(True)
self.paths = []
self.hbox = QHBoxLayout()
self.setLayout(self.hbox)
self.label = QLineEdit()
self.label.setAttribute(Qt.WA_MacShowFocusRect, 0)
self.hbox.addWidget(self.label)
self.setTitle("Drag and Drop")

def dropEvent(self, droppedstuff):
droppedEvent = droppedstuff
mimeData = droppedEvent.mimeData()
mimeData.hasUrls()
urls = droppedstuff.mimeData().urls()
if droppedstuff.mimeData().hasUrls():
droppedstuff.accept()
else:
droppedstuff.ignore()
for item in urls:
self.path = item.toLocalFile().rstrip("/")
self.label.setText(self.path)
pass

def dragEnterEvent(self, enteredstuff):
enteredstuff.accept()
pass

def dragMoveEvent(self, movedstuff):
movedstuff.accept()
pass
Written by Spencer.


No comments:

Post a Comment