Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Draw a rectangle when mouse is clicked
Forum Update on Monday, May 27th 2025

Draw a rectangle when mouse is clicked

Scheduled Pinned Locked Moved Unsolved General and Desktop
3 Posts 3 Posters 1.9k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Y Offline
    Y Offline
    YYYY
    wrote on 9 May 2019, 13:45 last edited by YYYY 5 Sept 2019, 14:11
    #1

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

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

    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)){
            update();
        }
    }
    

    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.

    1 Reply Last reply
    0
    • K Offline
      K Offline
      Kent-Dorfman
      wrote on 9 May 2019, 14:15 last edited by
      #2

      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.

      1 Reply Last reply
      4
      • M Offline
        M Offline
        mrjj
        Lifetime Qt Champion
        wrote on 9 May 2019, 14:21 last edited by
        #3

        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.

        1 Reply Last reply
        5

        3/3

        9 May 2019, 14:21

        • Login

        • Login or register to search.
        3 out of 3
        • First post
          3/3
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved