我有以下代码通过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
为红色。所有文本都应该在同一行。我该怎么办?
答案 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
以获取下一个字符串。