Can’t drag and drop elements in pyqt5 while in IDE

I have an issue with PyQt5 on Windows when starting my code from my PyCharm IDE. I am unable to drag stuff into the running program, detect the drag events, or get the mouse to show something else than the "forbidden" sign.

When the code is packed into an executable with pyinstaller or started from the command line, the drag and drop works as intended.

For testing purposes, I copied the code from this answer: I want to get and show images with Drag&Drop methods of pyqt5

I believe that the process within PyCharm gets somehow isolated from the environment, but I am not experienced enough to make assumptions this deep and wouldn't know how to solve such a problem.

This is the example code:

import sys

from PyQt5.QtCore import QSize
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtWidgets import QPushButton, QWidget, QLabel, QApplication


class Button(QPushButton):
    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(e.mimeData(), "Drag dropped")
        m = e.mimeData()
        if m.hasUrls():
            self.parent().label.setPixmap(QPixmap(m.urls()[0].toLocalFile()))
            self.parent().label.setScaledContents(True)

            
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        button = Button("", self)
        button.resize(100, 100)
        button.setIcon(QIcon("gazo1.jpg"))
        button.setIconSize(QSize(100, 100))
        button.move(0, 0)

        self.label = QLabel(self)
        self.label.move(150, 150)
        self.label.resize(QSize(300, 300))

        self.setWindowTitle('Simple drag & drop')
        self.setGeometry(300, 300, 300, 300)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    app.exec_()


Read more here: https://stackoverflow.com/questions/66267850/cant-drag-and-drop-elements-in-pyqt5-while-in-ide

Content Attribution

This content was originally published by T. Schmidbauer at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: