我有下面的代码通过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
红色。所有的文字都应该在同一行。我该怎么做?
最佳答案
我不知道有任何 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
中作为下一个字符串。
关于c++ - QPainter,给文本部分分配不同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25113772/