首页 > 解决方案 > 如何擦除 PyQt5 QPainter 中的点?

问题描述

我想在图像上显示加速度计的 x 和 y 坐标。我使用 QPainter 设置图像并使用 drawPoint 函数在给定点绘制坐标。绘制新坐标时,我需要擦除旧坐标,以便一次只有一个。在下面的代码中,我调用了 drawCoordinate 两次,发生的情况是目标图像在 0,0 和 0.5,0.5 处有 2 个坐标点,但理想情况下我会留下最后一个绘制的坐标。

这是我在这里的第一个问题,所以我希望我的格式是正确的!让我知道是否需要解决任何问题以帮助清晰。

具有 2 个坐标的目标图像


class Target(QWidget):

    def __init__(self):
        super().__init__()
        self.drawing = False
        self.image = QPixmap(r"Pictures\target_png_300.png")
        self.setGeometry(0, 0, 300, 300)
        self.resize(self.image.width(), self.image.height())
        self.show()

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), self.image)
    
    def paintCoordinate(self, x, y):
        painter = QPainter(self.image)
        r = QRect(-1, -1, 2, 2)
        painter.setWindow(r)
        pen = QPen(Qt.black, 0.06, Qt.DotLine, Qt.RoundCap)
        painter.setPen(pen)
        painter.drawPoint(QPointF(x, y))

if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    ex = Target()
    ex.paintCoordinate(0, 0)
    ex.paintCoordinate(0.5, 0.5)
    sys.exit(app.exec_())

标签: pythonqtpyqtpyqt5coordinates

解决方案


如果您只想要一个点,则不要修改 QPixmap,而只需在 paintEvent 方法中进行绘制:

class Target(QWidget):
    def __init__(self):
        super().__init__()
        self._pixmap = QPixmap()
        self._coordinate = QPointF()

    @property
    def pixmap(self):
        return self._pixmap

    @pixmap.setter
    def pixmap(self, pixmap):
        self._pixmap = pixmap.copy()
        self.update()
        size = self.pixmap.size()
        if size.isValid():
            self.resize(size)
        else:
            self.resize(300, 300)

    @property
    def coordinate(self):
        return self._coordinate

    @coordinate.setter
    def coordinate(self, point):
        self._coordinate = point
        self.update()

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), self.pixmap)
        r = QRect(-1, -1, 2, 2)
        painter.setWindow(r)
        pen = QPen(Qt.black, 0.06, Qt.DotLine, Qt.RoundCap)
        painter.setPen(pen)
        painter.drawPoint(self.coordinate)


if __name__ == "__main__":

    app = QApplication(sys.argv)
    ex = Target()
    ex.pixmap = QPixmap(r"Pictures\target_png_300.png")
    ex.coordinate = QPointF(0, 0)
    ex.coordinate = QPointF(0.5, 0.5)
    ex.show()
    sys.exit(app.exec_())

推荐阅读