How to draw a polyline ("open polygon") in a QGraphicsView

Viewed 515

is there a way to draw a line with multiple points and afterwards have the possibility to be able to catch that line with some kind of mouse-over-event?

Unfortunately I'm struggling to draw a line in a QGraphicsView with multiple intermediate points.

I know how to draw a closed polygon with QtWidgets.QGraphicsPolygonItem(QPolygonF...). If my polygon-points are not closed - that means the last point is not equal to the first one - the polygon gets closed automatically.

However I'd like to not have that last connection.

With QtWidgets.QGraphicsLineItem only a line between two points can be drawn.

2 Answers

One possible solution is to use 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_()

I took the idea and used this code:

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

In polyline I had already a QPolygonF-Object holding all points.

Related