PyQt5 tutorial "Drag & Drop"

 

table of Contents

 

Drag and drop in PyQt5

QDrag

Simple drag and drop

Drag and drop button widget


Drag and drop in PyQt5

In this part of the PyQt5 tutorial, we will discuss drag and drop operations.

In a computer graphical user interface, drag and drop is the act of clicking on a virtual object and dragging it to another location or another virtual object (or supporting its operation). In general, it can be used to invoke multiple operations or create various types of associations between two abstract objects.

Drag and drop is part of the graphical user interface. Drag and drop operations enable users to perform complex operations intuitively.

Usually, we can drag and drop two things: data or some graphic objects. If we drag images from one application to another, we drag and drop binary data. If we drag a label in Firefox and move it to another place, we will drag and drop a graphical component.

QDrag

QDragProvide support for MIME-based drag-and-drop data transmission. It handles most of the details of drag and drop operations. The transferred data is contained in the QMimeDataobject.

Simple drag and drop

In the first example, we have one QLineEditand one  QPushButton. We drag the plain text from the line editing widget and drop it on the button widget. The label of the button will change.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

from PyQt5.QtWidgets import (QPushButton, QWidget, 
    QLineEdit, QApplication)
import sys

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

    def dragEnterEvent(self, e):
      
        if e.mimeData().hasFormat('text/plain'):
            e.accept()
        else:
            e.ignore() 

    def dropEvent(self, e):
        
        self.setText(e.mimeData().text()) 


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

        edit = QLineEdit('', self)
        edit.setDragEnabled(True)
        edit.move(30, 65)

        button = Button("Button", self)
        button.move(190, 65)
        
        self.setWindowTitle('Simple drag and drop')
        self.setGeometry(300, 300, 300, 150)


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

This example provides a simple drag and drop operation.

class Button(QPushButton):
  
    def __init __(self,title,parent):
        super().__ init __(title,parent)
        
        ...

In order to delete QPushButtonthe text on the widget, we must reimplement some methods. Therefore, we create our own Button class, which will inherit from the QPushButtonclass.

self.setAcceptDrops(True)

We have enabled drop events for widgets setAcceptDrops().

def dragEnterEvent(self, e):
    
    if e.mimeData().hasFormat('text/plain'):
        e.accept()
    else:
        e.ignore() 

First, we reimplement the dragEnterEvent()method. We inform us of the type of data we accept. In our example, it is plain text.

def dropEvent(self, e):

    self.setText(e.mimeData().text()) 

By reimplementing this dropEvent()method, we define what happens to the drop event. Here, we change the text of the button widget.

edit = QLineEdit('', self)
edit.setDragEnabled(True)

The QLineEditwidget has built-in support for drag operations. All we need to do is call the setDragEnabled()method to activate it.

Simple drag and drop

Figure: Simple drag and drop

Drag and drop button widget

In the example below, we will demonstrate how to drag and drop a button widget.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

from PyQt5.QtWidgets import QPushButton, QWidget, QApplication
from PyQt5.QtCore import Qt, QMimeData
from PyQt5.QtGui import QDrag
import sys

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

    def mouseMoveEvent(self, e):

        if e.buttons() != Qt.RightButton:
            return

        mimeData = QMimeData()

        drag = QDrag(self)
        drag.setMimeData(mimeData)
        drag.setHotSpot(e.pos() - self.rect().topLeft())

        dropAction = drag.exec_(Qt.MoveAction)


    def mousePressEvent(self, e):
      
        super().mousePressEvent(e)
        
        if e.button() == Qt.LeftButton:
            print('press')


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

        self.initUI()
        
        
    def initUI(self):

        self.setAcceptDrops(True)

        self.button = Button('Button', self)
        self.button.move(100, 65)

        self.setWindowTitle('Click or Move')
        self.setGeometry(300, 300, 280, 150)
        

    def dragEnterEvent(self, e):
      
        e.accept()
        

    def dropEvent(self, e):

        position = e.pos()
        self.button.move(position)

        e.setDropAction(Qt.MoveAction)
        e.accept()
        

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

In our code example, we QPushButtonhave one in the window. If we click the button with the left mouse button, a "press" message will be printed on the console. By right-clicking and moving the button, we perform a drag and drop operation on the button widget.

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

We created a Buttonderived class QPushButton. We also re-implemented two methods QPushButton: mouseMoveEvent()and mousePressEvent(). This mouseMoveEvent()method is where the drag and drop operation begins.

if e.buttons() != Qt.RightButton:
    return

Here, we decided to use only the right mouse button to perform drag and drop operations. The left mouse button is reserved for clicking buttons.

mimeData = QMimeData()

drag = QDrag(self)
drag.setMimeData(mimeData)
drag.setHotSpot(e.pos() - self.rect().topLeft())

The QDragobject has been created. This class provides support for MIME-based drag-and-drop data transmission.

dropAction = drag.exec_(Qt.MoveAction)

exec_()Drag the object to start the drag and drop operation.

def mousePressEvent(self, e):
    
    super().mousePressEvent(e)
    
    if e.button() == Qt.LeftButton:
        print('press')

If we click the button with the left mouse button, we print "press" to the console. Note that we mousePressEvent()also call methods on the parent. Otherwise, we will not see the button being pressed.

position = e.pos()
self.button.move(position)

In this dropEvent()method, we specify what happens when the mouse button is released and the placement operation is completed. In our example, we find the current mouse pointer position and move the button accordingly.

e.setDropAction(Qt.MoveAction)
e.accept()

We use the specified type of placement operation setDropAction(). In our example, this is a move action.

 

Published 59 original articles · 69 praises · 270,000+ views

Guess you like

Origin blog.csdn.net/pansaky/article/details/98873595