python之pyQt5实例:鼠标创建点

实现一个基于PyQt5的画布,可以通过鼠标左键点击的方式创建点,并在画布中显示出来。

from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow,QInputDialog
from PyQt5.QtGui import QPainter, QBrush, QColor
from PyQt5.QtCore import Qt,QPoint
class Canvas(QWidget):
    def __init__(self):
        super().__init__()
        self.points = []  # 存储所有创建的点
​
    def paintEvent(self, event):
        qp = QPainter(self)
        qp.setRenderHint(QPainter.Antialiasing)  # 设置抗锯齿
        qp.fillRect(self.rect(), Qt.white)  # 填充背景为白色
        qp.setBrush(Qt.black)  # 设置画刷颜色为黑色
​
        for point in self.points:
            qp.drawEllipse(point, 5, 5)  # 绘制点
​
    def create_point_by_mousedown(self, pos):
        self.points.append(pos)
        self.update()  # 更新绘制
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.resize(800, 600)  # 设置窗口大小为 800x600 像素 
​
        self.canvas = Canvas()
        self.setCentralWidget(self.canvas)
​
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.canvas.create_point_by_mousedown(event.pos())
​
if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()

python之pyQt5实例:鼠标创建点_第1张图片

你可能感兴趣的:(python,qt,开发语言)