Selection area in Qt widget

2.6k views Asked by At

I have a problem with selection area.

If you click on your windows desktop, and drag mouse, you will see selection area. I'm trying to achieve generally similar thing.

Do you have any ideas how to achieve this?

2

There are 2 answers

0
Alexander V On BEST ANSWER

It is called "rubber band". You need to find an example for using QRubberBand class. I cannot separate a small sample from relatively big project but overall it is not very complex and simply works.

0
Nejat On

You can use QRubberBand. Here is an example from the Qt documentation when you want to implement it in your widget :

 void Widget::mousePressEvent(QMouseEvent *event)
 {
     origin = event->pos();
     if (!rubberBand)
         rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
     rubberBand->setGeometry(QRect(origin, QSize()));
     rubberBand->show();
 }

 void Widget::mouseMoveEvent(QMouseEvent *event)
 {
     rubberBand->setGeometry(QRect(origin, event->pos()).normalized());
 }

 void Widget::mouseReleaseEvent(QMouseEvent *event)
 {
     rubberBand->hide();
     // determine selection, for example using QRect::intersects()
     // and QRect::contains().
 }

If you are implementing it in an other class and want to be displayed in a widget you should be careful about the coordinate system. That's because event->pos() is in a different coordinate system than that of your widget, so instead of event->pos() you should use :

myWidget->mapFromGlobal(this->mapToGlobal(event->pos()))