PyQT:拖放:hasFormat

PyQT: Drag 'N Drop: hasFormat

我正在尝试创建一个只接受 PDF 文件的拖放标签。 为此,我尝试使用 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()

不过好像不行。

我用 mimeData().hasImage 试过一个图像文件,它有效。 .hasFormat 支持 pdf 文件吗?

你可以根据url得到mimetype并验证它是否对应一个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()