天天看點

PyQt5實作一個滑鼠輸入的塗鴉闆

PyQt5實作一個滑鼠輸入的塗鴉闆

說明:.ui檔案就是個空白widget,我是在Qt Designer中生成的。也可以在代碼中實 現。

資源在這裡:https://download.csdn.net/download/blueparrot/10751252

import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import uic, QtWidgets


qtCreatorFile = "d:/2D_draw_scrawl.ui"

Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)


class MyDraw(QtWidgets.QWidget, Ui_MainWindow):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

        self.pix = QPixmap(300, 300)
        self.pix.fill(QColor(255, 255, 255))
        self.endPoint = QPoint()
        self.lastPoint = QPoint()
        self.painter = QPainter()

    def paintEvent(self, event):
        self.painter.begin(self)
        self.painter.drawPixmap(0, 0, self.pix)
        self.painter.end()

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

    def mouseMoveEvent(self, event):
            if event.buttons() == Qt.LeftButton:       # 這裡隻能用buttons(), 因為button()在mouseMoveEvent()中無論
                self.endPoint = event.pos()            # 按下什麼鍵,傳回的都是Qt::NoButton
                self.painter.begin(self.pix)        # 注意這裡的參數必須是self.pix,塗鴉隻能在這個300*300的白闆上進行
                self.painter.setPen(QColor(0, 255, 0))
                self.painter.drawLine(self.lastPoint, self.endPoint)
                self.painter.end()
                self.update()
                self.lastPoint = self.endPoint

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


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = MyDraw()
    window.show()
    sys.exit(app.exec_())