143.Python-PySide6:鼠标事件绘图

本文主要演示一下PySide6窗体中的鼠标事件,通过鼠标操作在窗体上绘图。

实现的关键要点

  • 绘图事件:paintEvent
  • 鼠标事件:mousePressEvent,mouseMoveEvent,mouseReleaseEvent。
  • 鼠标返回的坐标点:event.pos()
  • 更新:update()
  • #定义画布、设置画笔、画线等基本方法

运行效果:

实现代码:

import sys
from PySide6 import QtCore,QtGui,QtWidgets

class MainWindow(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        
        self.setWindowTitle("Mouse Events")
        #设置窗口大小和位置居中
        screen=QtGui.QGuiApplication.primaryScreen().geometry()
        sw,sh=screen.width(),screen.height()
        w,h=800,600
        self.setGeometry((sw-w)//2,(sh-h)//2,w,h)
        
        #窗体上定义一个画布
        self.pix=QtGui.QPixmap(w,h)
        self.pix.fill(QtCore.Qt.white)
        
        #定义前后两点
        self.point0=QtCore.QPoint()
        self.point1=QtCore.QPoint()
        
    def paintEvent(self, event):
        #定义画布上绘图
        ppix=QtGui.QPainter(self.pix)
        #设置笔的风格
        ppix.setPen(QtGui.QPen(QtGui.QColor(255, 0, 0), 2, QtCore.Qt.SolidLine))
        ppix.drawLine(self.point0, self.point1)
        
        self.point0=self.point1 #交换前后坐标
        painter=QtGui.QPainter(self)
        
        painter.drawPixmap(0,0,self.pix)
        
    #鼠标点击事件
    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton: #左键,起点位置
            self.point0 = event.pos()
            self.point1=self.point0
            
    #鼠标移动事件
    def mouseMoveEvent(self, event):
        if event.buttons() and QtCore.Qt.LeftButton: #按住左键移动
            self.point1=event.pos()
            self.update() #重新绘制
            
    #鼠标释放事件
    def mouseReleaseEvent(self, event):
        if event.button()== QtCore.Qt.LeftButton: #释放左键
            self.point1=event.pos()
            self.update() 
            

if __name__ == '__main__':
    app=QtWidgets.QApplication(sys.argv)
    mywin=MainWindow()
    mywin.show()
    sys.exit(app.exec())
        

程序运行的警告信息说明:

#警告信息:pos() 弃用警告 
DeprecationWarning: Function: 'pos() const' is marked as deprecated, please check the doc
umentation for more information.

#查询官网文档说明:这里并没有说pos()被弃用,
PySide6.QtGui.QMouseEvent.pos()
RETURN TYPE
PySide6.QtCore.QPoint

Returns the position of the mouse cursor, relative to the widget that received the event.
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章