I'm trying to create a drag 'n drop label which accepts only PDF files.
To do that I try using the mimeData().hasFormat
.
def dragEnterEvent(self, event):
if event.mimeData().hasFormat(application/pdf):
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasFormat(application/pdf):
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasFormat(application/pdf):
event.setDropAction(Qt.CopyAction)
file_path = event.mimeData().urls()[0].toLocalFile()
self.set_path(file_path)
event.accept()
else:
event.ignore()
It does not seem to work though.
I tried it with mimeData().hasImage
for an image file and it works.
Does .hasFormat
support pdf files?
CodePudding user response:
You can get the mimetype based on the url and verify that it corresponds to a pdf:
from PyQt5.QtCore import QMimeDatabase
from PyQt5.QtWidgets import QApplication, QLabel
class Label(QLabel):
def __init__(self, parent=None):
super().__init__(parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if self.find_pdf(event.mimeData()):
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if self.find_pdf(event.mimeData()):
event.accept()
else:
event.ignore()
def dropEvent(self, event):
urls = self.find_pdf(event.mimeData())
if urls:
for url in urls:
print(url.toLocalFile())
event.accept()
else:
event.ignore()
def find_pdf(self, mimedata):
urls = list()
db = QMimeDatabase()
for url in mimedata.urls():
mimetype = db.mimeTypeForUrl(url)
if mimetype.name() == "application/pdf":
urls.append(url)
return urls
def main():
app = QApplication([])
label = Label()
label.resize(640, 480)
label.show()
app.exec_()
if __name__ == "__main__":
main()