Congratulations to our 2022 Qt Champions!

Multiple Rectangles Appearing On Mouse Move

  • Hello every one, I am new to qt c++. So as usual, I am facing problems :) I am developing a very simple paint application for desktop using qt gui application. I am ok with drawing free hand, but when I tried to draw rectangle on mouse move, multiple rectangles appearing! I need help to solve this problem. I want to know why this is happening!

    My code looks like below :

    void MainWindow::mouseMoveEvent(QMouseEvent *e)
    QPen pen(mColor);
    mEnd = e->pos();
    QRect rect(mBegin.x(), mBegin.y(), mEnd.x(), mEnd.y());
    mBegin = mEnd;

    Someone please help me to solve this problem. Thanks in advance :)

  • Hi,
    this is happening bacause you draw a new rectangle on every MouseMove. What you need is a Rubberband during mouse moves and drawing the rectangle in response to MouseRelease.
    The Documentation of QRubberband should give you a hint how to do that.

  • Thanks Gerd, for providing me the clue :)

  • @Gerd
    Thanks Gerd, for providing me the clue :)

  • @Gerd
    Mouse Release Event is OK, but it does not mean it :( I want to show the drawings while mouse is moving, but not after releasing the mouse! And QRubberBand::Shape has line and rectangle not other shapes! I am not getting any idea how I will solve it !

  • Not sure what you mean.
    In your initial post you are talking about rectangles, so the way to do that is this:

    • on MousePressEvent start a rubberBand
    • on mouseMoveEvent update the rubberBand rectangle
    • on mouseReleaseEvent hide the rubberBand, take the geometry of the rubberBand and draw your rectangle with this geometry

    If you need to do this with other shapes you have to implement the background saving and restore by yourself, but thats another question...

  • @Gerd
    Yes it is Ok, what you have given as a solution is ok, but I have told I am developing paint tool, that is why besides rectangles I will need other shapes too :)

    Thank you for your guidence. I am trying to solve this. And obviously your suggestion was very helpful, though I could not properly utilize!

  • Lifetime Qt Champion

    maybe you can be inspired by this sample

Log in to reply