【问题标题】:QPainter, assigning different colors to text partsQPainter,为文本部分分配不同的颜色
【发布时间】:2014-09-26 15:17:25
【问题描述】:

我有下面的代码通过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 为红色。所有文本都应该在同一行。我该怎么做?

【问题讨论】:

    标签: c++ qt colors qpainter


    【解决方案1】:

    我不知道有任何 Qt 类/函数可以为你工作,所以你可以自己做:

    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 以获取下一个字符串。

    【讨论】:

    • 谢谢,它工作正常,但是你如何添加间距?
    • 只需更改字符串。例如QString texts [ 3 ] = { "1 ", "2 ", "3 " };。或许多其他方式。这取决于您的实际代码中最有意义的部分。
    • “另类”的方式是使用Qt的富文本类(QTextDocument、QTextLine、QTextLayout)来布局具有多种格式的线条并进行绘制。
    • @peppe 富文本类对于我的问题范围来说似乎有点过分了。 +1 提及他们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    相关资源
    最近更新 更多