Search code examples
c++qtqt5qgraphicssceneqcolor

How to draw filled polygon on QGraphicsScene


I want to draw a polygon filled with a specific color on QGraphicsScene. Then I use the following codes:

QPolygonF poly;
poly << QPointF(10, 10) << QPointF(10, 50) << QPointF(30, 70 )<< QPointF(60, 50) << QPointF(50, 10);
QBrush brush;
brush.setColor(Qt::red);
QPen pen(Qt::green);
QGraphicsScene graphics_scene_ = new QGraphicsScene(0,0,200,200);
graphics_scene_->addPolygon(poly, pen, brush);
setScene(graphics_scene_);

However I only get a hollow polygon with green border, but without red fill inside the polygon. How can I fix it?


Solution

  • QBrush() is missing the style. You should use:

    QBrush brush
    brush.setColor(Qt::red);
    brush.setStyle(Qt::SolidPattern);
    

    Or better this way since the Qt::SolidPattern style comes by default:

    QBrush brush(Qt::red);