python - 如何在 QGraphicsView 中绘制折线(“开放多边形”)
问题描述
有没有办法用多点画一条线,然后有可能通过某种鼠标悬停事件来捕捉这条线?
不幸的是,我正在努力在具有多个中间点的 QGraphicsView 中画一条线。
我知道如何用QtWidgets.QGraphicsPolygonItem(QPolygonF...)
. 如果我的多边形点没有关闭——这意味着最后一个点不等于第一个点——多边形会自动关闭。
但是我不想有最后一个连接。
只能在QtWidgets.QGraphicsLineItem
两点之间画一条线。
解决方案
一种可能的解决方案是使用 QPainterPath:
import random
from PyQt5 import QtGui, QtWidgets
class GraphicsPathItem(QtWidgets.QGraphicsPathItem):
def mousePressEvent(self, event):
super().mousePressEvent(event)
print("Local position:", event.pos())
print("Scene position:", event.scenePos())
def shape(self):
if self.path() == QtGui.QPainterPath():
return self.path()
pen = self.pen()
ps = QtGui.QPainterPathStroker()
ps.setCapStyle(pen.capStyle())
width = 2 * max(0.00000001, pen.widthF())
ps.setWidth(width)
ps.setJoinStyle(pen.joinStyle())
ps.setMiterLimit(pen.miterLimit())
return ps.createStroke(path)
app = QtWidgets.QApplication([])
scene = QtWidgets.QGraphicsScene()
view = QtWidgets.QGraphicsView(scene)
view.setRenderHint(QtGui.QPainter.Antialiasing)
view.resize(640, 480)
view.show()
path_item = GraphicsPathItem()
path_item.setPen(QtGui.QPen(QtGui.QColor("red"), 5))
path = QtGui.QPainterPath()
path.moveTo(0, 0)
for i in range(5):
x, y = random.sample(range(300), 2)
path.lineTo(x, y)
path_item.setPath(path)
scene.addItem(path_item)
app.exec_()
推荐阅读
- ios - 如果在 iOS 中足够高,如何将 PDFKit 注释跨越 2 页
- javascript - 当我导航到另一个页面时,计数器继续计数
- c# - 在 C# 中使用 byte[] 进行内存碎片
- audio - 记录从缓冲区处理的音频结果并将其放置在音频元素中
- c++ - 如何防止调试器进入codelite中的“@file ext/new_allocator.h”和“@file bits/vector.tcc”等头文件?
- javascript - CanvasJS 动态加载数据 MVC Razor
- sharepoint - 使用 ms-word 协议直接在 Desktop Word 中打开位于 oneDrive/sharepoint 中的文档
- python - 根据时间戳选择数据后,无法使用地理数据框几何调用 LineString(来自 shapely)
- json - 需要 AWS S3 QuickSight 清单文件 URI?
- events - CALL METHOD 和 -> 对于 ALV 事件的行为不同。为什么?