https://github.com/2minchul/PyQt5-Examples/blob/master/%5BPyQt5%5D%20get%20filepath%20by%20Drag%26Drop/app.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/python3
#-*- coding: utf-8 -*-
 
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
 
class MainWidget(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWidget, self).__init__(parent)
        self.setWindowTitle("title")
        self.resize(720,480)
        self.setAcceptDrops(True)
 
    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.accept()
        else:
            event.ignore()
 
    def dropEvent(self, event):
        files = [u.toLocalFile() for u in event.mimeData().urls()]
        for f in files:
            print(f)
 
if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = MainWidget()
    MainWindow.show()
    sys.exit(app.exec_())
cs


  1. ㅇㅇ 2022.01.28 12:45

    원하는 기능을 하는 코드 찾느라 힘들었는데 겨우 찾았네요 감사합니다

  2. superiorcho 2022.07.07 11:58

    아래 QTDesigner로 생성한 파일에 응용해 보았는데 왜 드래그앤드롭 동작을 하지 않는걸까요? ㅠㅠ
    label위에 드랍 했을때 파일 명을 출력하는 코드를 만들고 싶어요..

    import sys
    from PyQt5 import QtCore, QtGui, QtWidgets


    class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
    MainWindow.setObjectName("MainWindow")
    MainWindow.resize(167, 149)
    MainWindow.setStyleSheet("background-color:#DDC6B6")
    self.centralwidget = QtWidgets.QWidget(MainWindow)
    self.centralwidget.setObjectName("centralwidget")
    self.label = QtWidgets.QLabel(self.centralwidget)
    self.label.setGeometry(QtCore.QRect(35, 37, 61, 21))
    self.label.setObjectName("label")
    self.label.setAcceptDrops(True)
    MainWindow.setCentralWidget(self.centralwidget)

    self.statusbar = QtWidgets.QStatusBar(MainWindow)
    self.statusbar.setObjectName("statusbar")
    MainWindow.setStatusBar(self.statusbar)

    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
    _translate = QtCore.QCoreApplication.translate
    MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
    self.label.setText(_translate("MainWindow", "TextLabel"))




    def dragEnterEvent(self, event):
    if event.mimeData().hasUrls():
    event.accept()
    else:
    event.ignore()

    def dropEvent(self, event):
    files = [u.toLocalFile() for u in event.mimeData().urls()]
    for f in files:
    print(f)




    if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

+ Recent posts