import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Drawing(QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
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()
# 進行重新繪製
self.update()
if __name__ == "__main__":
app = QApplication(sys.argv)
main = Drawing()
main.show()
sys.exit(app.exec_())