Not able to draw lines inside QPaintEvent



  • Refer the code below

    draw.h

    #ifndef DRAW_H
    #define DRAW_H

    #include <QWidget>
    #include <QPainter>
    #include <QLabel>
    #include <QDebug>

    namespace Ui {
    class Draw;
    }

    class Draw : public QWidget
    {
    Q_OBJECT

    public:
    explicit Draw(QWidget *parent = 0);
    ~Draw();

    void line();
    void paintEvent(QPaintEvent *e);
    void drawLabel();
    
    int flag = 0;
    

    private slots:
    void on_pushButton_clicked();

    private:
    Ui::Draw *ui;
    };

    #endif // DRAW_H

    draw.cpp

    #include "draw.h"
    #include "ui_draw.h"

    Draw::Draw(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Draw)
    {
    ui->setupUi(this);
    }

    Draw::~Draw()
    {
    delete ui;
    }

    void Draw::paintEvent(QPaintEvent *e)
    {
    QPainter *painter = new QPainter(this);
    if(flag == 1)
    {
    painter->setPen(QPen(Qt::black, 1));
    painter->drawLine(20, 50, 70, 50);
    painter->drawLine(120, 50, 170, 50);
    drawLabel();
    }
    }

    void Draw::drawLabel()
    {
    QLabel *label = new QLabel(this);
    label->setStyleSheet("border: 1px solid black");
    label->setGeometry(70, 40, 50, 20);
    label->show();
    }

    void Draw::on_pushButton_clicked()
    {
    flag = 1;
    }

    main.cpp

    #include "draw.h"
    #include <QApplication>

    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);
    Draw w;
    w.show();

    return a.exec();
    

    }

    I am trying to draw a label between two lines, when a push button is clicked. but when I am clicking the pushbutton I am seeing only label, the two lines are missing. Please help me to achieve this.



  • Try this:

    void Draw::on_pushButton_clicked()
    {
        flag = 1;
        update();
    }
    


  • Thanx, it really solved my problem


Log in to reply
 

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