Using Qt, how do I resize a widget using the mouse move event going up or to the left

I have a QMainWindow that has a QWidget. The QWidget appears, and has its origin set in the mouse down event of the QMainWindow. Then, in the mouse move event of the QMainWindow, the geometry of the QWidget is set, such that it appears that the user is drawing a rectangle on top of the QMainWindow. This is how I'm doing it:

void MyQMainWindow::mousePressEvent(QMouseEvent * E) {
    QPoint pos = e->pos();
    myQWidget->setGeometry(pos.x(), pos.y(), 0, 0);
    myQWidget->show();
}

void MyQMainWindow::mouseMoveEvent(QMouseEvent * e) {
    QPoint pos = e->pos();
    QPoint prv = myQWidget->pos();
    int w = pos.x() - prv.x();
    int h = pos.y() - prv.y();

    myQWidget.setGeometry(prv.x(), prv.y(), w, h);
}

void MyQMainWindow::mouseReleaseEvent(QMouseEvent *) {
    myQWidget.hide();
}

The problem with this approach is that when I drag the mouse up, or left of where I clicked. My calculations for w and h are negative, and so the window does not resize correctly (or at all).

I realize that moving up/left would mean that I need to change the origin of the widget, while keeping the bottom right corner of it in the same place by also increasing the width/height as needed, but how do I do this?

Thanks!

Answers


I would do something like this:

 void MyQMainWindow::updateWidgetGeometry()
 {
      if (_initial == QPoint(-1,-1)) {
          return;
      }

      x = qMin(_initial.x(), _current.x());
      y = qMin(_initial.y(), _current.y());
      w = abs(_initial.x() - _current.x());
      h = abs(_initial.y() - _current.y());

      myQWidget.setGeometry(x, y, w, h);    
 } 

 void MyQMainWindow::mousePressEvent(QMouseEvent * E)
 {
      _initial = e->pos();
      _current = e->pos();
      updateWidgetGeometry()
      myQWidget->show();
 } 

 void MyQMainWindow::mouseMoveEvent(QMouseEvent * E)
 {
      _current= e->pos();
      updateWidgetGeometry()
 }

 void MyQMainWindow::mouseReleaseEvent(QMouseEvent *) 
 {
     _current = QPoint(-1,-1);
     _initial = QPoint(-1,-1);
     myQWidget.hide();
 } 

Typed this up without a compiler.

By the way, you might also need to setMouseTracking(true) so that if your mouse move event happens inside the widget your MyQMainWindow gets to handle it. I'm not sure about that bit.


Need Your Help

download flash video using php readfile

php flash readfile

i am trying to download flv video to the flash player using PHP's readfile() function, using this i can hide the location of the file. i tried these codes but jw player don't work, file can downloa...

providing critical section for threads in c++

c++ multithreading mutex

In this c++ program , I have created 10 threads which race to each other to acquire critical section.For this mean I'm using conditional variable as below code.The dispatcher in this program will g...