【已解决】pyqt5界面拖拽文件进入时,显示禁止图标,槽函数也没有进入。怎么办? | 您所在的位置:网站首页 › 拖拽文件到这里怎么弄出来 › 【已解决】pyqt5界面拖拽文件进入时,显示禁止图标,槽函数也没有进入。怎么办? |
我今天遇到了一个很无语的问题,不知道为啥,用 QMainwindow 创建了一个简单的界面,里面只有一个 Qlabel。 想要尝试拖拽文件进来,然后打印文件路径。但是怎么改都没反应。一直显示禁止的一个图标,类似于: 如果你也和我一样,建议你不要较劲,删掉自己所有代码,尝试用下面的代码测试一下,如果测试通过,就在这个代码基础上去修改吧。 这段代码在我这里是可以打印出拖拽进入的文件路径的: 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): print(e.mimeData(), "Drag Entered") m = e.mimeData() if m.hasUrls(): e.accept() else: e.ignore() def dropEvent(self, e): print("dropEvent") m = e.mimeData() if m.hasUrls(): print("hasUrls") e.accept() print("正在处理") links = [] for url in e.mimeData().urls(): links.append(str(url.toLocalFile())) self.handleFiles(links) else: e.ignore() def handleFiles(self, files): for file in files: print(file) class Example(QWidget): def __init__(self): super().__init__() self.setAcceptDrops(True) self.initUI() def initUI(self): l = MyLabel("", self) l.resize(300, 300) l.move(0, 0) self.setGeometry(300, 300, 300, 300) if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() ex.show() app.exec_()路径就打印出来啦: |
CopyRight 2018-2019 实验室设备网 版权所有 |