1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > PyQt实现按钮控件的拖动效果 利用鼠标移动事件实现。

PyQt实现按钮控件的拖动效果 利用鼠标移动事件实现。

时间:2020-03-12 03:13:56

相关推荐

PyQt实现按钮控件的拖动效果 利用鼠标移动事件实现。

文章目录

原理代码

原理

1、利用mousePressEvent记录下鼠标按下时在控件上的相对位置;

2、利用mouseMoveEvent记录下鼠标移动中的位置,并且将控件移动到那个位置。不过要当心的是,这种情况下不能使用布局。

3、如果你希望自行实现流程框图之类可以拖拽的东西,在pyqt中,除了pyqtgraph自带的流程图,也可以尝试一下使用这种可拖动的控件来进行绘制。这样,圆角和圆形效果就可以直接绘制出来了。

代码

import sysfrom PyQt5.QtWidgets import QPushButton, QWidget, QApplicationfrom PyQt5.QtCore import Qt, QMimeData,QPointfrom PyQt5.QtGui import QDragimport timeclass DraggableButton(QPushButton):def __init__(self, title, parent):super().__init__(title, parent)self.iniDragCor=[0,0] def mousePressEvent(self,e):print("ppp",e.pos())self.iniDragCor[0]=e.x()self.iniDragCor[1]=e.y()def mouseMoveEvent(self, e):x=e.x()-self.iniDragCor[0]y=e.y()-self.iniDragCor[1]cor=QPoint(x,y) self.move(self.mapToParent(cor))# 需要maptoparent一下才可以的,否则只是相对位置。print('drag button event,',time.time(),e.pos(),e.x(),e.y())class DragWidget(QWidget):def __init__(self):super().__init__()self.initUI()def initUI(self):self.button1 = DraggableButton("mybutton", self)self.button1.move(50, 20)self.setWindowTitle("Click or Move")self.setGeometry(300, 300, 280, 150)def mouseMoveEvent(self,e):print('main',e.x(),e.y())if __name__ == "__main__":app = QApplication(sys.argv)ex = DragWidget()ex.show()app.exec_()

效果:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。