Skip to content Skip to sidebar Skip to footer

I Want To Get And Show Images With Drag&drop Methods Of Pyqt5

I want to get and show images with Drag&Drop methods of pyqt5. For example,like this image, I want to make Drag&Drop space and Image-show space. import sys from PyQt5.Q

Solution 1:

As you want to drag an image from the desktop, the path of this image provides it through a local url, to verify it uses the mimeData(). hasUrls(), and urls() to get the url, then we get the local path with the method toLocalFile(), all the above is implemented in the following code:

class Button(QPushButton):
    def __init__(self, title, parent):
        super().__init__(title, parent)
        self.setAcceptDrops(True)

    def dragEnterEvent(self, e):
        m = e.mimeData()
        if m.hasUrls():
            e.accept()
        else:
            e.ignore()

    def dropEvent(self, e):
        m = e.mimeData()
        if m.hasUrls():
            self.parent().label.setPixmap(QPixmap(m.urls()[0].toLocalFile())) 


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.setPixmap(QPixmap('gazo2.png'))
        self.label.move(150,150)

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


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

Post a Comment for "I Want To Get And Show Images With Drag&drop Methods Of Pyqt5"