Search code examples
c++qtqt4drawing

How to bind or merge QPainterPaths?


I'm trying to create brushed arch in my widget so that it occupies top part of it. I've managed to draw it, but having difficult with filling it. Can you help me?

void Curve::paintEvent(QPaintEvent *) {

     QPainter painter(this);
     painter.setRenderHint(QPainter::Antialiasing);
     painter.setPen(QPen(QColor("#4681c5"), 2.5, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin));  /// #4681c5    

     QPainterPath path;
     path.moveTo(width()/2 + 85.2, 71);
     path.cubicTo(width()/2 + 86.2, 71, width()/2 + 97, 102, width()/2 + 137, 102);

     QPainterPath path2;
     path2.moveTo(width()/2 - 85.2, 71);
     path2.cubicTo(width()/2 - 86.2, 71, width()/2 - 97, 102, width()/2 - 137, 102);

     QPainterPath path3;
     path3.arcMoveTo(width()/2 - 95, 18, 190, 190, 26);
     path3.arcTo(width()/2 - 95, 18, 190, 190, 26, 128);

     QPolygonF leftpoly;
     leftpoly << QPointF(0, 0) << QPointF(0, 102) << QPointF(width()/2 - 137, 102);

     QPolygonF rightpoly;
     rightpoly << QPointF(width()/2 + 137, 102) << QPointF(width(), 102) << QPointF(width(), 0) << QPointF(0, 0);

     QPainterPath arch;
     arch.connectPath(path2);
     arch.connectPath(path3);
     arch.connectPath(path);
     QPainterPath fill;
     fill.addPolygon(leftpoly);
     fill.connectPath(arch);
     fill.addPolygon(rightpoly);
     painter.fillPath(fill, QBrush(QColor("#f68448")));

     path.addPolygon(rightpoly);
     path2.addPolygon(leftpoly);
     path3.addPath(path);
     path3.addPath(path2);
     painter.drawPath(fill);
}

The result of the code above is as follows:

enter image description here

I would like to fill it properly.

P.S. I've tried the method simplified, connectPath even united but all didn't worked.


Solution

  • You need to be more careful about the way in which subpaths are directed when you connect them to form larger paths. In particular, look at the beginning and end points of path, path2 and path3 in your code and then look at the order in which you connect them.

    In this case you should be able to correct things by reversing path2 and path3 when combining them to form arch...

    QPainterPath arch;
    arch.connectPath(path2.toReversed());
    arch.connectPath(path3.toReversed());
    arch.connectPath(path);
    

    Output with reversed paths