[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
    {
    public:
    myLabel(QWidget *parent = 0);

    protected:
    void drawLabel(QPaintEvent *event);

    private:
    QLabel *label;
    };

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

    }

    void myLabel::drawLabel(QPaintEvent *e)
    {
    Q_UNUSED(e);

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

    }

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

    myLabel labelMy;
    
    labelMy.resize(300,300);
    labelMy.show();
    
    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);
    label->setPixmap(myPix);
    

    }
    @

    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
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.