首页 > 解决方案 > 如何在 QGraphicsView 中绘制折线(“开放多边形”)

问题描述

有没有办法用多点画一条线,然后有可能通过某种鼠标悬停事件来捕捉这条线?

不幸的是,我正在努力在具有多个中间点的 QGraphicsView 中画一条线。

我知道如何用QtWidgets.QGraphicsPolygonItem(QPolygonF...). 如果我的多边形点没有关闭——这意味着最后一个点不等于第一个点——多边形会自动关闭。

但是我不想有最后一个连接。

只能在QtWidgets.QGraphicsLineItem两点之间画一条线。

标签: pythonpyqt5polylineqgraphicsitem

解决方案


一种可能的解决方案是使用 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_()

推荐阅读