What I want: Drag a file into label area, and get the file directory.
The problem is: I have 2 Class, 1 is for drag&drop function, the other one is for creating ui window. I don't know how to apply the drag&drop function to the label inside the ui.
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QLabel
# class that add drag&drop function to QLabel
class Label_draghere(QLabel):
def __init__(self, parent):
super().__init__(parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.acceptProposedAction()
def dropEvent(self, event):
# print file directory
lines = []
for url in event.mimeData().urls():
lines.append('dir: %r' % url.toLocalFile())
print(lines)
# class that create ui window
class Win_excelCheck:
def __init__(self):
# load ui (there's only 1 Label named label_drag1 in the ui, nothing else)
self.ui = uic.loadUi('ui/label_win.ui')
self.ui.setAcceptDrops(True)
# This line is wrong, what I'm tring to do is apply Label_draghere Class to label_drag1 widget
self.ui.label_drag1 = Label_draghere(self.ui)
if __name__ == '__main__':
app = QApplication([])
mainWin = Win_excelCheck()
mainWin.ui.show()
app.exec_()
Code Result: This code has no error message showed up, but when I drag file into the Label, there's a red prohibition sign next to my cursor and doesn't allow me to drop anything. img_drop_prohibited
My reference: I wrote this code by referring to this:
https://www.jb51.net/article/226682.htm .But all the tutorials use addWidget
to create ui instead of uic.loadUi
, and I need to use uic way, so I don't know how to modify the code.
Please help, really appreciate ^_^