有没有办法用多个点画一条线,然后有可能通过某种鼠标悬停事件捕捉到这条线?
不幸的是,我正在努力在具有多个中间点的 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_()
关于python - 如何在 QGraphicsView 中绘制折线 ("open polygon"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64144063/