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 Updated to NodeBB v4.3 + New Features

Draw a rectangle when mouse is clicked

Scheduled Pinned Locked Moved Unsolved General and Desktop
3 Posts 3 Posters 1.9k Views 2 Watching
  • 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 last edited by YYYY
    #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
    • Kent-DorfmanK Offline
      Kent-DorfmanK Offline
      Kent-Dorfman
      wrote on 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
      • mrjjM Offline
        mrjjM Offline
        mrjj
        Lifetime Qt Champion
        wrote on 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

        • Login

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