Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selection area in Qt widget

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?

like image 399
Tatarinho Avatar asked Dec 05 '25 12:12

Tatarinho


1 Answers

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()))

like image 53
Nejat Avatar answered Dec 07 '25 06:12

Nejat