Qt World Summit: Register Today!

[SOLVED]Drawing in QLabel

  • Hello, I am having some difficulties with a program I am writing. I am writing a very simple program, what I want is to draw inside a QLabel a rectangle and paint it.

    #include <QApplication>
    #include <QLabel>
    #include <QPainter>
    #include <QHBoxLayout>
    #include <QPixmap>

    class myLabel : public QWidget
    myLabel(QWidget *parent = 0);

    void drawLabel(QPaintEvent *event);

    QLabel *label;

    myLabel::myLabel(QWidget *parent):QWidget(parent)


    void myLabel::drawLabel(QPaintEvent *e)

    QPainter *painter = new QPainter();
    QPixmap *myPix = new QPixmap();
    painter->drawRect(10, 15, 10, 10);
    myPix->fill(painter, 20,20);
    label = new QLabel("", this);


    int main(int argc, char *argv[])
    QApplication a(argc, argv);

    myLabel labelMy;
    return a.exec&#40;&#41;;



    I read I can draw inside a QLabel with QPixmap by using the setPixmap() function of the label. I am having difficulties doing that, I would like to know how it is done. Please keep your answers simple. Thank You.

  • Moderators

    you never call drawLabel() .. .at least in the code you posted

    you're creating an QPainter which has no paint device (see the docs) to paint to

    void myLabel::drawLabel()
    QPixmap myPix( QSize(20,20) );

    QPainter painter(myPix);
    painter.setBrush( Qt::red );
    painter.drawRect(5, 5, 10, 10);
    label = new QLabel("", this);


    But i would subclass QLabel and override it's paintEvent handler .... unless you need a label object inside your custom widget?

  • raven-worx

    Thank you for replying back the code you provided worked fine.

Log in to reply