如何在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_()
,

我接受了这个想法并使用了以下代码:

path = QtGui.QPainterPath()
path.addPolygon(polyline)
new_item = QtWidgets.QGraphicsPathItem(path,None)
new_item.setPath(path)
scene.addItem(new_item)

polyline中,我已经拥有一个包含所有点的QPolygonF-Object。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...