python - 如何擦除 PyQt5 QPainter 中的点?
问题描述
我想在图像上显示加速度计的 x 和 y 坐标。我使用 QPainter 设置图像并使用 drawPoint 函数在给定点绘制坐标。绘制新坐标时,我需要擦除旧坐标,以便一次只有一个。在下面的代码中,我调用了 drawCoordinate 两次,发生的情况是目标图像在 0,0 和 0.5,0.5 处有 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_())
解决方案
如果您只想要一个点,则不要修改 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_())
推荐阅读
- javascript - 为什么我在 react 中运行 npm start 时会出错?
- jquery - 如何在没有任何插件或其他插件的情况下制作 Swipe 幻灯片?
- java - 如何从不同的片段访问 Room 数据库?
- .net - 如何将 MS Teams 对话参考保存在数据库中?
- reactjs - 如果基于对象调用 setState(Obj),则不会调用 useEffect
- spring - feign 客户端 - 从服务中检索 jwt 令牌并在 feign 客户端中自动设置它
- html - 我想做一个冻结的标题
- python - 如何将jupyter笔记本颜色主题放入vs代码
- azure - 如何调用 azure web 作业并传递参数
- sharepoint - SPFolder.MoveTo 保留子文件夹的元数据,同时重置根文件夹的元数据