Search code examples
c++qtcolorsqpainter

QPainter, assigning different colors to text parts


I have the below code to display some text via QPainter

QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.setPen(QColor(10, 10, 10, 255)); // text color
painter.fillRect(QRect(10, 10, 200, 100), QColor(100, 100, 100, 120)); //rectangular color
painter.setFont(font);
painter.drawText(20, 20,  "1 2 3 4");

I want to display each part of the text via different color, e.g. 1 in black, 2 in white, 3 in blue, and 4 in red. All the text should be in the same line. How can I do it?


Solution

  • I don't know any Qt class/func that does this work for you, so you can just do it yourself:

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.fillRect(QRect(10, 10, 200, 100), QColor(100, 100, 100, 120)); //rectangular color
    
    
    QColor  colors [ 3 ]        = { QColor(255, 0, 0, 255), QColor(0, 255, 0, 255), QColor(0, 0, 255, 255) };
    QString texts [ 3 ]         = { "1", "2", "3" };
    QFontMetrics fontmetrics    ( painter.font () );
    int     y                   = 20,
            x                   = 20;
    
    for ( int i = 0; i < 3; ++ i )
    {
        painter.setPen ( colors [ i ] );
        painter.drawText ( x, y, texts [ i ] );
    
        x += fontmetrics.width ( texts [ i ] );
    }
    

    Above code is using QFontMetrics to calculate the length in pixels of the inserted text, and then adds it to x for the next string.