目录
一、实战场景
实战场景:Python 中 PyQt6 的拖放按钮组件
二、主要知识点
三、菜鸟实战
创建文件!
import sys
from PyQt6.QtCore import Qt, QMimeData
from PyQt6.QtGui import QDrag
from PyQt6.QtWidgets import QPushButton, QWidget, QApplication
class Button(QPushButton):
def __init__(self, title, parent):
super().__init__(title, parent)
def mouseMoveEvent(self, e):
if e.buttons() != Qt.MouseButtons.RightButton:
return
mimeData = QMimeData()
drag = QDrag(self)
drag.setMimeData(mimeData)
drag.setHotSpot(e.position().toPoint() - self.rect().topLeft())
dropAction = drag.exec(Qt.DropActions.MoveAction)
def mousePressEvent(self, e):
super().mousePressEvent(e)
if e.button() == Qt.MouseButtons.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, 550, 450)
def dragEnterEvent(self, e):
e.accept()
def dropEvent(self, e):
position = e.position()
self.button.move(position.toPoint())
e.setDropAction(Qt.DropActions.MoveAction)
e.accept()
def main():
app = QApplication(sys.argv)
ex = Example()
ex.show()
app.exec()
if __name__ == '__main__':
main()
本例中,窗口里有个 QPushButton
,鼠标左键点击它,会在控制台打印 'press'消息,鼠标右键可以点击拖拽它。
class Button(QPushButton):
def __init__(self, title, parent):
super().__init__(title, parent)
基于 QPushButton
创建了一个 Button
类,并实现了两个 QPushButton
方法:mouseMoveEvent
和 mousePressEvent
。mouseMoveEvent
方法是处理拖放操作开始的地方。
if e.buttons() != Qt.MouseButtons.RightButton:
return
定义鼠标右键为触发拖拽操作的按钮,鼠标左键只会触发点击事件。
drag = QDrag(self)
drag.setMimeData(mimeData)
drag.setHotSpot(e.position().toPoint() - self.rect().topLeft())
创建 QDrag
对象,以提供基于 MIME 数据类型的拖拽操作。
dropAction = drag.exec(Qt.DropActions.MoveAction)
drag
对象的 exec
方法执行拖拽操作。
def mousePressEvent(self, e):
super().mousePressEvent(e)
if e.button() == Qt.MouseButtons.LeftButton:
print('press')
如果鼠标左键点击按钮,会在控制台打印 'press' 消息,注意,这里在父级上也调用了 mousePressEvent
方法,不然按钮按下的动作不会展现出来。
position = e.pos() self.button.move(position)
dropEvent
方法处理鼠标释放按钮后的操作————把组件的位置修改为鼠标当前坐标。
e.setDropAction(Qt.MoveAction) e.accept()
使用 setDropAction
指定拖放操作的类型————鼠标移动。
菜鸟实战,持续学习!