QPainter,为文本部分指定不同的颜色

时间:2014-08-04 07:36:28

标签: c++ qt colors qpainter

我有以下代码通过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");

我希望通过不同的颜色显示文本的每个部分,例如1为黑色,2为白色,3为蓝色,4为红色。所有文本都应该在同一行。我该怎么办?

1 个答案:

答案 0 :(得分:1)

我不知道任何Qt class / func可以帮到你,所以你可以自己动手:

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 ] );
}

上面的代码使用QFontMetrics来计算插入文本的长度(以像素为单位),然后将其添加到x以获取下一个字符串。