How to resize a QGraphicsRectItem using the mouse

665 Views Asked by At

I am developing a Graphical User Interface (GUI) which allows the user to draw several rectangles and resize them using the mouse pointer.

The code for drawing the rectangles works perfectly. However, when it comes to resizing some unwanted bugs appear.

Here is my code:

void ImageGraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event){


      if(startModifying==true){

         if(isOnTopLeftCornerPressed==true){

            QRectF rectF_buffer(rectModified->rect().bottomRight().x(),rectModified->rect().bottomRight().y(),event->scenePos().x()-rectModified->rect().bottomRight().x(),event->scenePos().y()-rectModified->rect().bottomRight().y());
            rectModified->setRect(rectF_buffer.normalized());

         }
         if(isOnTopRightCornerPressed==true){

            QRectF rectF_buffer(rectModified->rect().bottomLeft().x(),rectModified->rect().bottomLeft().y(),event->scenePos().x()-rectModified->rect().bottomLeft().x(),event->scenePos().y()-rectModified->rect().bottomLeft().y());
            rectModified->setRect(rectF_buffer.normalized());

         }
         if(isOnBottomRightCornerPressed==true){

            QRectF rectF_buffer(rectModified->rect().topLeft().x(),rectModified->rect().topLeft().y(),event->scenePos().x()-rectModified->rect().topLeft().x(),event->scenePos().y()-rectModified->rect().topLeft().y());
            rectModified->setRect(rectF_buffer.normalized());

         }   
         if(isOnBottomLeftCornerPressed==true){

            QRectF rectF_buffer(rectModified->rect().topRight().x(),rectModified->rect().topRight().y(),event->scenePos().x()-rectModified->rect().topRight().x(),event->scenePos().y()-rectModified->rect().topRight().y());
            rectModified->setRect(rectF_buffer.normalized());

         }   

       }
}

startModifying:

This variable checks if the user is in the "modifying mode".

isOnTopLeftCornerPressed/isOnTopRightCornerPressed/isOnBottomRightCornerPressed/isOnBottomLeftCornerPressed:

These variables check if the user has pressed with the mouse pointer one of the rectangle corners (Top Right, Top Left, Bottom Right and Bottom Left).

rectModified

It is a QGraphicsRectItem

With this code the user can resize the rectangle:

The user can resize the rectangle when the height and width are botth positive or negative

However, when the height or the width become negative during the resizing, it stops working: The user is not able to resize the rectangle when the height or the width are positive and negative or negative and positive respectively

The mouseMoveEvent() gets called. However, when width()<0, the "normalized" function does not swap the left and right corners, and neither the top and bottom corners if height()<0 as it is said in Qt documentation.

Could you help me please ?

0

There are 0 best solutions below