I'm subclassing QProgressBar in a custom widget, and I overwrote the paintEvent method with the following code :
void myProg::paintEvent(QPaintEvent *pe)
{
QProgressBar::paintEvent(pe);
QRect region = pe->rect();
QPainter *painter = new QPainter(this);
QPen *pen = new QPen;
painter->begin(this);
painter->setBrush(Qt::red);
int x = this->x();
int y = this->y();
pen->setWidth(10);
painter->setPen(*pen);
painter->drawLine(x,y,x+100,y);
painter->end();
}
I'm trying to display a red line, as a starting point, to see that I can add my own modifications to the widget. However, this isn't working. I only see the widget as a regular QProgressBar. Any ideas on what could be wrong ?
The coordinate system you need to use is relative to the top-left of the widget, but you're apparently using one relative to the widget's parent. (Widget's x and y coords are relative to their parent). So your line will be getting clipped.
Also, it's unnecessary to call QPainter::begin and QPainter::end when you construct it using a QWidget * parameter. And the painter in your code doesn't get deleted, either. It's not necessary to create a painter on the heap with new
: I'd just create it on the stack.
Try:
void myProg::paintEvent(QPaintEvent *pe) { QProgressBar::paintEvent(pe); QRect region = pe->rect(); QPainter painter(this); QPen pen(Qt::red); //Note: set line colour like this //(Brush line removed; not necessary when drawing a line) int x = 0; //Note changed int y = height() / 2; //Note changed pen.setWidth(10); painter.setPen(pen); painter.drawLine(x,y,x+100,y); }
This should draw a red horizontal line 100 pixels long starting from the middle-left of the widget.