PyQt5学习笔记(09)--Drag and drop

本文代码来自zetcode.com


QDrag

QDrag提供基于MIME类型的拖放数据传送,它能处理大多数拖放操作,QMimeData对象包含了传送的数据。


Simple drag and drop

在本例中,我们有QLineEditQPushButton,当我们从编辑框拖放文本放入按钮控件,按钮的标签就会改变。


"""
This is a simple drag and drop example.
"""

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


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_()

为了实现拖放文本到QPushButton控件,我们必需重新实现一些方法。
因此我们创建继承了QPushButtonButton类。


PyQt5学习笔记(09)--Drag and drop_第1张图片


Drag and drop a button widget

#!/usr/bin/python3

"""
In this program, we can press on a button with a left mouse
click or drag and drop the button with right mouse click.
"""

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


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(10, 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_()

本例实现了鼠标左键为点击,鼠标右键为拖拽功能

你可能感兴趣的:(Python)