B
B
Babay2018-10-22 19:42:11
Python
Babay, 2018-10-22 19:42:11

How to write a drag and drop application?

You need to write something like a quiz in python, using this library, that is, there are pictures and a field with a name from all the pictures you need to take one correct one and drag it to the name. Please explain the principle of how it should work from the point of view of the program logic or throw links to information, preferably in Russian.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-10-22
@Babaq

import sys

from PyQt5.QtWidgets import QApplication, QLabel, QWidget
from PyQt5.QtGui import QDrag, QPixmap, QImage, QPainter, QCursor
from PyQt5.QtCore import QMimeData, Qt


class DraggableLabel(QLabel):
    def __init__(self, parent, image):
        super(QLabel, self).__init__(parent)
        self.setPixmap(QPixmap(image).scaledToWidth(64))    
        self.show()

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.drag_start_position = event.pos()

    def mouseMoveEvent(self, event):
        if not (event.buttons() & Qt.LeftButton):
            return
        if (event.pos() - self.drag_start_position).manhattanLength() < QApplication.startDragDistance():
            return
        drag = QDrag(self)
        mimedata = QMimeData()
        mimedata.setText(self.text())
        mimedata.setImageData(self.pixmap().toImage())

        drag.setMimeData(mimedata)
        pixmap = QPixmap(self.size())
        painter = QPainter(pixmap)
        painter.drawPixmap(self.rect(), self.grab())
        painter.end()
        drag.setPixmap(pixmap)
        drag.setHotSpot(event.pos())
        drag.exec_(Qt.CopyAction | Qt.MoveAction)


class DropLabel(QLabel):
    def __init__(self, *args, **kwargs):
        QLabel.__init__(self, *args, **kwargs)
        self.setAcceptDrops(True)

    def dragEnterEvent(self, event):
        if event.mimeData().hasImage():
            print('event accepted')
            event.accept()
        else:
            print('event rejected')
            event.ignore()

    def dropEvent(self, event):
        if event.mimeData().hasImage():
            self.setPixmap(QPixmap.fromImage(QImage(event.mimeData().imageData())))


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

    def initUI(self):
        label = DropLabel('drop there', self)
        label.setGeometry(190, 65, 100, 100)

        label_to_drag = DraggableLabel(self, 'image.png')
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

G
GromderCom, 2018-10-25
@GromderCom

The wxPython interface toolkit has built-in Drag'n'drop:
https://python-scripts.com/wxpython-how-to-use-dra...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question