3
votes

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!

1

1 Answers

1
votes

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.