本文共 2377 字,大约阅读时间需要 7 分钟。
通常,我们可以拖放两件事:数据或一些图形对象。如果我们把一个图像从一个应用程序到另一个地方,我们拖拽二进制数据。如果我们把一个标签在Firefox中并将其移动到另一个地方,我们拖拽一个图形组件
输入文本后拖拽到button
import sysfrom 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("drag here", self) button.move(190, 65) self.setWindowTitle('Simple drag & drop') self.setGeometry(300, 300, 300, 150)if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() ex.show() app.exec_()文本kuang 输入完成后全选,拖拽 拖拽button,鼠标右键拖拽
import sysfrom PyQt5.QtWidgets import QPushButton, QWidget, QApplicationfrom PyQt5.QtCore import Qt, QMimeDatafrom 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): QPushButton.mousePressEvent(self, 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_()
转载地址:http://woben.baihongyu.com/