Selecting a region from a QGraphicScene with QRubberBand
-
Hello everyone,
I'm trying to select a region of an image in a QGraphicScene with QRubberBand. Following the documentation ( http://doc.qt.io/qt-5/qrubberband.html ) I wrote this:
void MainWindow::mousePressEvent(QMouseEvent *event) { mypoint = event->pos(); mRubberBand = new QRubberBand(QRubberBand::Rectangle, ui->graphicsView);//new rectangle band mRubberBand->setGeometry(QRect(mypoint, QSize())); mRubberBand->show(); } void MainWindow::mouseMoveEvent(QMouseEvent *event) { if(mRubberBand) { mRubberBand->setGeometry(QRect(mypoint, event->pos()).normalized());//Area Bounding } } void MainWindow::mouseReleaseEvent(QMouseEvent *event) { if(mRubberBand) { QRect myRect(mypoint, event->pos()); mRubberBand->hide();// hide on mouse Release QImage copyImage; //<= this Qimage hold nothing mImageInRect = copyImage.copy(myRect); } }
The problem is the code work ONLY if I start selecting out of the GraphicScene and then move, I can't click to the image and start selecting.
Someone could please explain me what's wrong? Thank you
-
You are overriding the mouse*Events in the MainWindow. If you want to detect a mouse press in a QGraphicsView then override mousePressEvent in QGraphicsView (by subclassing it).
Also, you modified the example and created a severe memory drain. You are creating new rubber band object on every mouse press and they will be deleted only when the parent graphics view is destroyed.
-