Search code examples
c++qtqpainter

Qt drawing a ring / circle with a hole


I need to draw a circle with QPainter. When I used drawEllipse function like :

void UserClass::Draw(QPainter &painter) {

    painter.save();
    painter.setBrush( GetColor() );
    QPoint centerPosition = GetCenterPosition();
    painter.drawEllipse( centerPosition, m_CircleOuterRadius, m_CircleOuterRadius);
    painter.setBrush(QColor(0, 0, 0, 0));
    painter.drawEllipse( centerPosition, m_CircleInnerRadius, m_CircleInnerRadius);
    painter.restore();  
}

Unfortunately result is not what I desired. I want to have inner circle not be filled. That is why I put alpha value as zero but ofcourse it didn't work. How can I have a circle which is not until a certain radius with qt ?

enter image description here


Solution

  • You should create a QPainterPath then add the two circles to it via addEllipse(), the outer first, then the inner. This will effectively give you a shape that is the outer circle with the inner circle punched as a hole.

    Then you fill the painter path with a green brush, which will result in a hollow ring. Afterwards, if you want the white outlines, you can stroke the path with a white pen as well.

    Also note that the painter path can be created only once and stored for reuse instead of creating it anew every time you redraw.