Important: Please read the Qt Code of Conduct -

Draw a rectangle when mouse is clicked

  • I wanna draw a rectangle on the main window when the mouse button is clicked, and my paintEvent is

    QPainter painter;
    QPen notePen(...);
    painter.drawRect(m_lastPoint.x(), m_lastPoint.y(), 20, 20);

    where m_lastPoint is the position where I clicked the mouse, and my mousePressEvent and mouseReleaseEvent are

    void MainWindowWidget::mousePressEvent(QMouseEvent *event){
        m_lastPoint = event->pos();
        m_mouseClick = true;
    void MainWindowWidget::mouseReleaseEvent(QMouseEvent *event){
        if(m_mouseClick && (event->pos() == m_lastPoint)){

    What I want to ask is, when I first clicked the mouse and clicked the mouse again, I want to maintain the rectangle that I drew at the first mouse click. In my code, the rectangle I drew before disappears.

  • to save previous drawing entities that you have created you need to create a backing store image and paint into that backing, then draw that backing image to the main widget in on every update. IOW, successive updates will COMPLETELY update the widget so you need to have a secondary image buffer to hold the accumulated stuff.

  • Lifetime Qt Champion

    Hi and welcome to the forums
    you could also just use a list
    QList<QRect> rects;
    and store the rects in there and then in
    paintEvent, loop the list and draw the rects.

Log in to reply