Search code examples
qtqpainterqlabel

Overriding QLabel to be able to draw graphs


I want to draw a graph on my main form, so I figured I'd use a QLabel and Override that. Like this:

// drawlabel.h
class DrawLabel : public QLabel
{
    Q_OBJECT
    public:
        DrawLabel(QWidget *parent = 0);
    private:
        void paintEvent(QPaintEvent *);
};

// drawlabel.cpp
DrawLabel::DrawLabel(QWidget *parent)
    : QLabel(parent)
{
}

void DrawLabel::paintEvent(QPaintEvent *)
{
    qDebug() << "paint event" ;

    QPainter painter(this);
    painter.setPen(QPen(QBrush(QColor(0,0,0,180)),1,Qt::DashLine));

    painter.setBrush(QBrush(QColor(255,255,255,120)));

    QRect selectionRect(10, 10, 100, 101);

    painter.drawRect(selectionRect);
}

On my main window I droppde a QLabel, sized it to about 500x200 and promoted it to DrawLLabel. When the application is run, a dashed square is drawn on the form.

All good so far.

If I add the line: this->setText("123456");

into the DrawLabel constructor, or add it into the paintEvent() I don't see the text. I'd also like to be able to have a border around the DrawLabel, but

this->setFrameShape(QFrame::Box);

in the constructor doesn't work either.

What should I be doing to get these to work?


Solution

  • Well, I think you should call paintEvent of base class. Add parameter name e to method:

    void DrawLabel::paintEvent(QPaintEvent *e)
    

    And then at end of method add

    QLabel::paintEvent (e);
    

    The second option do all painting by yourself directly at paintEvent.