Python | How to extract path by Drag and Drop

GUI App

This article describes how to extract the path by Drag and Drop in a Python GUI application.

Example

We will now make the following app.

Code

  1. import urllib.parse.
  2. set self.setAcceptDrops(True).
  3. set dragEnterEvent accept().
  4. set dropEvent accept() and write the code to be performed after the drop.
#!/usr/bin/env python3

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QLabel
from PyQt6.QtGui import QPainter
import urllib.parse                                                    # 1


class GuiWindow(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setGeometry(0, 0, 300, 300)
        self.build_ui()
        self.setAcceptDrops(True)                                      # 2

    def build_ui(self):
        self.qlb_name = QLabel('Yoshihiko', self)
        self.qlb_name.setGeometry(40, 30, 250, 20)

        self.job = 'Hero'
        self.qlb_job = QLabel('job : ' + self.job, self)
        self.qlb_job.setGeometry(40, 80, 250, 20)

        self.qlb_item = QLabel('item : ', self)
        self.qlb_item.setGeometry(40, 130, 250, 20)

        self.qlb_message = QLabel('', self)
        self.qlb_message.setGeometry(40, 230, 250, 50)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawRoundedRect(25, 20, 250, 200, 10, 10)
        painter.drawLine(40, 63, 260, 63)

    def dragEnterEvent(self, event):                                   # 3
        event.accept()

    def dropEvent(self, event):                                        # 4
        event.accept()
        self.a_QMimeData      = event.mimeData()
        self.b_binary_CRLF    = self.a_QMimeData.data('text/uri-list')
        self.c_binary         = self.b_binary_CRLF.simplified()
        self.d_string_percent = str(self.c_binary, 'utf-8')
        self.e_string          = urllib.parse.unquote(self.d_string_percent)
        self.f_path            = self.split_path(self.e_string)
        self.g_filename       = self.extract_filename(self.f_path)
        self.update_job()
        self.update_item(self.g_filename)
        self.update_message(self.g_filename)

    def split_path(self, string):
        file_path = string
        # marking for spliting(Windows)
        file_path = file_path.replace('file:///C', '|:div:|C')
        file_path = file_path.replace('file:///D', '|:div:|D')
        file_path = file_path.replace('file:///E', '|:div:|E')
        file_path = file_path.replace('file:///F', '|:div:|F')
        # marking for spliting(Mac)
        file_path = file_path.replace('file:///', '|:div:|/')
        # marking for spliting(server)
        file_path = file_path.replace('file:', '|:div:|')
        # split by marking
        file_path = file_path.split(' |:div:|')
        # delete |:div:| that remains at the first element
        file_path[0] = file_path[0].replace('|:div:|', '')
        file_path.sort()
        file_path = file_path[0]
        return file_path

    def extract_filename(self, file_path):
        filename_with_extension = file_path.split('/')[-1]
        filename = filename_with_extension.split('.')[0]
        return filename

    def update_job(self):
        self.job = 'Sage'
        self.qlb_job.setText('job : ' + self.job)

    def update_item(self, item):
        self.qlb_item.setText('item : ' + item)

    def update_message(self, item):
        self.qlb_message.setText('Yoshihiko read ' + item +'\n'\
                                 'Yoshihiko is now a sage.')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = GuiWindow()
    window.show()
    sys.exit(app.exec())

Extract path

Extracting the path in step #4. The contents of each variable are as follows.

self.a_QMimeData<PyQt6.QtCore.QMimeData object at 0x*********>
self.b_binary_CRLFb’file:///Users/yoshihiko/Desktop/Words%20of%20Wisdom.pdf\r\n’
self.c_binaryb’file:///Users/yoshihiko/Desktop/Words%20of%20Wisdom.pdf’
self.d_string_percentfile:///Users/yoshihiko/Desktop/Words%20of%20Wisdom.pdf
self.e_stringfile:///Users/yoshihiko/Desktop/Words of Wisdom.pdf
self.f_path/Users/yoshihiko/Desktop/Words of Wisdom.pdf
self.g_filenameWords of Wisdom

Summary

This article described how to extract the path by Drag and Drop in a Python GUI application.

コメント