pyqt5拖入文件demo

MyLabel 如果设置的dragEnterEvent,父类就获取不到了

MyLabel设置的dragEnterEvent取消了,父类就可以正常获取监听了。

import sys
from PyQt5.QtWidgets import QPushButton, QWidget, QLabel, QApplication


class MyLabel(QLabel):
    def __init__(self, title, parent):
        super().__init__(title, parent)
        self.setAcceptDrops(True)

    # def dragEnterEvent(self, e):
    #     m = e.mimeData()
    #     if m.hasUrls():
    #         e.accept()
    #     else:
    #         e.ignore()
    #
    # def dropEvent(self, e):
    #     m = e.mimeData()
    #     if m.hasUrls():
    #         e.accept()
    #         links = []
    #         for url in e.mimeData().urls():
    #             links.append(str(url.toLocalFile()))
    #         self.handleFiles(links)
    #     else:
    #         e.ignore()

    def handleFiles(self, files):

        print('label handle')
        show_txt=''
        for file in files:
            show_txt+=file+'\n'
        self.setText(show_txt)


class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.setAcceptDrops(True)
        self.initUI()

    def dragEnterEvent(self, e):
        m = e.mimeData()
        if m.hasUrls():
            e.accept()
        else:
            e.ignore()

    def dropEvent(self, e):
        m = e.mimeData()
        if m.hasUrls():
            e.accept()
            links = []
            for url in e.mimeData().urls():
                links.append(str(url.toLocalFile()))
            self.handleFiles(links)
        else:
            e.ignore()

    def handleFiles(self, files):
        print('QWidget handle')
        show_txt=''
        for file in files:
            show_txt+=file+'\n'
        self.label.setText(show_txt)
    def initUI(self):
        self.label = MyLabel("", self)
        self.label.resize(500, 300)
        self.label.move(0, 0)
        self.setGeometry(300, 300, 500, 300)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    app.exec_()

你可能感兴趣的:(python基础,qt,python,开发语言)