PyQt5基礎學習-繪圖應用 1.QPixmap(構造畫板) 2.QPainter().drawLine(在畫板上畫出直線) 3.mousePressEvent(鼠標的按下事件) 4.mouseMoveEvent(鼠標移動事件) 5.mouseReleaseEvent(鼠標釋放事件)


通過鼠標的點擊,來獲得直線的初始化位置, 通過鼠標的移動事件,獲得當前的位置,獲得完位置后進行繪圖,同時再更新初始化的位置

Drawing.py 

"""
項目實戰: 實現繪圖應用

需要解決3個核心內容
1.如何繪圖
2.在哪里繪圖
3.如果通過鼠標進行繪圖
"""

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPainter, QPixmap
from PyQt5.QtCore import Qt, QPoint

class Drawing(QWidget):
    def __init__(self):
        super(Drawing, self).__init__()
        self.setWindowTitle("繪圖應用")
        self.pix = QPixmap()
        # 畫布大小為400*400, 背景為白色
        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.button and Qt.LeftButton:
            self.endPoint = event.pos()
            self.update()

    def mouseReleaseEvent(self, event):
        #鼠標左鍵釋放,在進行最后一次繪制
        if event.button() == Qt.LeftButton:
            self.endPoint = event.pos()
            #進行重新繪制
            self.update()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = Drawing()
    form.show()
    sys.exit(app.exec_())

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM