PyQT5 (九十二) 项目实战:实现绘图应用 的案例

项目实战:实现绘图应用 的案例

需要解决3个核心内容
1.如何绘图

在paintEvent方法中绘图,通过调用update方法出发painEvent的条用

2.在哪里绘图

在白色北京的QPixmap对象中绘图

3.如何通过移动鼠标进行绘图

鼠标拥有3个事件:
(1) 鼠标按下 mousePressEvent
(2) 鼠标移动 mouseMoveEvent
(3) 鼠标抬起 mouseReleaseEvent


'''
项目实战:实现绘图应用 的案例

需要解决3个核心内容
1.如何绘图

在paintEvent方法中绘图,通过调用update方法出发painEvent的条用

2.在哪里绘图

在白色北京的QPixmap对象中绘图

3.如何通过移动鼠标进行绘图

鼠标拥有3个事件:
(1) 鼠标按下 mousePressEvent
(2) 鼠标移动 mouseMoveEvent
(3) 鼠标抬起 mouseReleaseEvent

'''
import sys

from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QIcon, QPixmap, QPainter
from PyQt5.QtWidgets import QWidget, QLineEdit, QPushButton, QGridLayout, QDialog, QApplication, QMainWindow, \
    QVBoxLayout


class DrawingDemo(QWidget):
    def __init__(self,parent=None):
        super(DrawingDemo,self).__init__(parent)
        # 设置窗口标题
        self.setWindowTitle('绘图应用 的演示')

        self.pix = QPixmap()
        self.lastPoint = QPoint()
        self.endPoint = QPoint()
        self.initUI()

    def initUI(self):
        # 设置定位和左上角坐标
        self.resize(600,600)
        # 画布大小为400*400 , 背景为白色
        self.pix = QPixmap(600,600)
        self.pix.fill(Qt.white)

    def paintEvent(self, event):
        pp = QPainter(self.pix)
        # 根据鼠标指针前后两个位置绘制直线
        pp.drawLine(self.lastPoint,self.endPoint)

        # 让前一个坐标等于后一个坐标值
        # 这样就能实现出连续的线
        self.lastPoint = self.endPoint
        painter = QPainter(self)
        painter.drawPixmap(0,0,self.pix)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.lastPoint = event.pos()

    def mouseMoveEvent(self, event):
        if event.buttons() and Qt.LeftButton:
            self.endPoint = event.pos()
            self.update()

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.endPoint = event.pos()




if __name__ == '__main__':
    app = QApplication(sys.argv)
    # 设置应用图标
    app.setWindowIcon(QIcon('../web.ico'))
    w = DrawingDemo()
    w.show()
    sys.exit(app.exec_())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值