Search code examples
c++qtqt5qgraphicssceneqgraphicsitem

How to get round caps with QGraphicsPolygonItem?


I have code like this:

#include <QApplication>
#include <QGraphicsPolygonItem>
#include <QGraphicsScene>
#include <QGraphicsView>

int main(int argc, char ** argv)
{
    QApplication app(argc, argv);
    
    QGraphicsScene scene;
    QGraphicsView view;

    view.resize(640, 400);
    view.setScene(&scene);

    auto polygon = new QGraphicsPolygonItem;
    auto brush = QBrush(QColor(255, 0, 0));
    polygon->setBrush(brush);
    auto pen = QPen(brush, 20);
    pen.setCapStyle(Qt::RoundCap);
    polygon->setPen(pen);

    QPolygonF polygonPath;
    polygonPath << QPointF{-50, -50};
    polygonPath << QPointF{100, -50};
    polygonPath << QPointF{100, 100};
    polygonPath << QPointF{-50, 100};

    polygon->setPolygon(polygonPath);

    scene.addItem(polygon);

    view.show();

    return app.exec();
}

Despite my round cap setting the polygon item gets rendered with straight caps.

Am I doing something obvious wrong here?


Solution

  • Not entirely sure but to get the result you're looking for when using a polygon path I think it's actually the 'join' style that needs to be set rather than the cap style. So change...

    pen.setCapStyle(Qt::RoundCap);
    

    to...

    pen.setJoinStyle(Qt::RoundJoin);