[Python] Operations concerning dropping file on PySide GUI

Discussão em 'Python' iniciado por Stack, Setembro 16, 2024.

  1. Stack

    Stack Membro Participativo

    I would like to know if it's possible to get a file's path by dragging it and dropping it inside a window made with PySide6. If not, how would I got about reading its bytes (in case of images) or its contents (in case of txt).

    I tried following the implemantation shown here (How to get dropped file names in PyQt/PySide), but I can't even drop the thing. What am I doing wrong?

    Here's the logic of the main window:

    class MainWin(QMainWindow):
    def __init__(self):
    super().__init__()
    self.setAcceptDrops(True)

    main_size = QSize(450,450)

    self.setWindowTitle("Image Recoder/Decoder")
    self.setFixedSize(QSize(500, 500))

    self.file_zone = QPushButton()
    self.file_zone.setFixedSize(main_size)
    self.file_zone.setIcon(QIcon("drag drop.png"))
    self.file_zone.setIconSize(main_size)
    self.file_zone.setStyleSheet("QPushButton {border: 0px; background-color: transparent}")
    self.file_zone.setCursor(QCursor(Qt.PointingHandCursor))
    self.file_zone.clicked.connect(self.main_logic)
    self.file_zone.setAcceptDrops(True)

    self.main_layout = QVBoxLayout()
    self.main_layout.addWidget(self.file_zone)
    self.main_layout.setAlignment(Qt.AlignCenter)

    container = QWidget()
    container.setLayout(self.main_layout)

    self.setCentralWidget(container)

    def main_logic(self):
    file_path = QFileDialog.getOpenFileName(self, filter="Images (*.png, *.jpg, *.jpeg);; Text (*.txt)")[0]
    file_split = os.path.splitext(file_path)

    if file_split[1] == ".txt":
    with open(file_path, 'r') as f:
    image_s = f.read()

    with open(r"{}.jpeg".format(file_split[0]), "wb") as f:
    f.write(base64.b64decode(image_s))
    else:
    with open(file_path, "rb") as f:
    image = f.read()
    image_s = str(base64.b64encode(image).decode("utf-8"))

    with open(r"{}.txt".format(file_split[0]), "w") as f:
    f.write(image_s)

    def dragEnterEvent(self, event):
    print('drag-enter')
    if event.mimeData().hasUrls():
    print('has urls')
    event.accept()
    else:
    event.ignore()

    def dropEvent(self, event):
    lines = []
    for url in event.mimeData().urls():
    lines.append('dropped: %r' % url.toLocalFile())
    print(lines)


    Like this, the button won't even accept the drop. Doing self.file_zone.setAcceptDrops(True) doesn't chage it either

    Continue reading...

Compartilhe esta Página