I am facing problem for drawing line and text with different color using QPainter. I am using the following piece of code to achieve this but it's not working. Both lines and texts are drawn using the color set for drawing Text.
void MyWidget::drawHorLinesWithText(QPainter & painter, const QRect & rect)
{
for(int i=0; i < 5; i++)
{
QPen penHLines(QColor("#0e5a77"), 1, Qt::DotLine, Qt::FlatCap, Qt::RoundJoin);
painter.setPen(penHLines);
painter.drawLine(10, 50 - (5*(i+1)), 200, 50 - (5*(i+1)));
QString strNumber = QString::number((2)*(i+1));
painter.setFont(QFont("Arial", 8, QFont::Bold));
//QBrush brush(QColor("#00e0fc"));
//painter.setBrush(brush);
QPen penHText(QColor("#00e0fc"));//Here lines are also drawn using this color
painter.setPen(penHText);
painter.drawText(5, 50 - (5*(i+1)) - 10), 20, 30, Qt::AlignHCenter | Qt::AlignVCenter,
strNumber);
}
}
How would I set different colors for drawing lines and Texts. Any suggestions. Thanks.
This works for me with Qt 5.3; perhaps it was a bug in the version you were using?
#include <QtWidgets>
class Widget : public QWidget
{
public:
Widget() {
resize(200, 200);
}
void paintEvent(QPaintEvent *) {
QPainter painter(this);
for(int i=0; i < 5; i++)
{
QPen penHLines(QColor("#0e5a77"), 10, Qt::DotLine, Qt::FlatCap, Qt::RoundJoin);
painter.setPen(penHLines);
painter.drawLine(10, 50 - (5*(i+1)), 200, 50 - (5*(i+1)));
QString strNumber = QString::number((2)*(i+1));
painter.setFont(QFont("Arial", 8, QFont::Bold));
QPen penHText(QColor("#00e0fc"));
painter.setPen(penHText);
painter.drawText(5, 50 - (5*(i+1)) - 10, 20, 30, Qt::AlignHCenter | Qt::AlignVCenter, strNumber);
}
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Widget w;
w.show();
return app.exec();
}
I increased the line width to 10 to see what's going on:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With