Drawn with a click event



  • Hi,

    How can I draw something when a buttons is clicked?

    I have this which drawn as soon as the app shows but I would like to be able to draw it only when a buttons isclicked.

    @void MainWindow::paintEvent(QPaintEvent *event)
    {
    QPainter painter( this);
    painter.setPen( Qt::red );
    painter.setBrush( Qt::green );
    painter.drawRect(10, 10, 100, 100);
    }@

    I tried this but I know I need to some how connect the paintEvent. I read the documetnation but I'm very confused.
    @void MainWindow::on_pushButton_Draw_clicked()
    {
    QPainter painter( this);
    painter.setPen( Qt::red );
    painter.setBrush( Qt::green );
    painter.drawRect(10, 10, 100, 100);
    }@

    Thanks a lot



  • You can trigger a paintEvent by calling repaint() or update().

    If something different should be drawn after after the button has been clicked, use member variable.

    @MainWindow::MainWindow(QObject *parent)
    {
    m_flag = false;
    }

    void MainWindow::paintEvent(QPaintEvent *event)
    {
    QPainter painter( this);
    if(!m_flag) {
    painter.setPen( Qt::green );
    painter.setBrush( Qt::green );
    painter.drawRect(10, 10, 100, 100);
    } else {
    painter.setPen( Qt::red );
    painter.setBrush( Qt::red );
    painter.drawRect(10, 10, 100, 100);
    }
    }

    void MainWindow::on_pushButton_Draw_clicked()
    {
    m_flag = true;
    update();
    }@



  • That worked, Thanks a lot.

    Now, is there a way to remove the rectangles with another pushButton?

    Thank you for your help!


  • Moderators

    Well, it depends on what you mean by "remove" the rectangles. You're just painting on the widget, so whatever was there before was obliterated by your paint (unless you do some magic to capture the previous widget contents to a Pixmap or something.) In order to remove them you have to repaint the contents of your widget so that the rectangles are not drawn.

    Edit to add:

    But it might be as simple as:
    @
    void MainWindow::on_pushButton_Remove_clicked()
    {
    m_flag = false;
    update();
    }
    @



  • That works, thanks a lot for your help!



  • One more question.

    Is there a way to change the stack order of the rectangles?

    In other words I'm currently painting the rectangles on the MainWIndow, the problem is that I have a tabWidget which was drawn using Qt Designer and I would like to have the rectangles to be drawn on top because right now the tabWidget is covering the recs.

    Is this possible or can I draw directly on the tabWidget?

    Thanks


Log in to reply
 

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