Search code examples
c++qtqt5qpainterqpainterpath

qt drawing outlined text with QPainterPath


i have to draw outlined striked out text on QImage like that:

enter image description here

I do it as follows:

QPainter painter(this);

QPainterPath path;

QFont font;
font.setPixelSize(95);
font.setStrikeOut(true);
font.setBold(true);

path.addText(10, 150, font, "lololo");

painter.setPen(Qt::blue);
painter.setBrush(Qt::red);

painter.drawPath(path);

and get this result:

enter image description here

As one can see the striking out line has zebra-like fill. How i can fill it completely with painter's brush?

I tried to change QPainter composition mode with no success. Also i tried to use QPainterPathStroker with the same result.

Sure i can draw striked out text with ordinary font (not striked out) plus rectangle, but it isn't a beautiful solution.


Solution

  • The solution is to perform operations between 2 paths with and without strike:

    #include <QtWidgets>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        QImage image(300, 200, QImage::Format_ARGB32);
        image.fill(Qt::transparent);
    
        QPoint p(30, 150);
        QString text = "lololo";
    
        QFont font;
        font.setPixelSize(95);
        font.setBold(true);
    
        QPainterPath path1;
        font.setStrikeOut(true);
        path1.addText(p, font, text);
        font.setStrikeOut(false);
        QPainterPath path2;
        path2.addText(p, font, text);
    
        QPainterPath strike = (path1 + path2) - (path1 & path2);
        //                      \---join---/    \-intersection-/
        QPainter painter(&image);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.setPen(Qt::blue);
        painter.setBrush(Qt::red);
        painter.drawPath(path2);
        painter.drawPath(strike);
        painter.end();
    
        QLabel w;
        w.setPixmap(QPixmap::fromImage(image));
        w.show();
    
        return a.exec();
    }
    

    enter image description here