4

I want to keep my QMainWindow always inside of the desktop, so I add the implementation for QMainWindow::moveEvent :

void MainWindow::moveEvent(QMoveEvent *ev)
{
    if(ev->pos().x() < 0) setGeometry(0, ev->oldPos().y(), width(), height());
}

But when I move the window to out of desktop left bounding, the app is crashed.
What is wrong with this code? Why it is crashed? Is my solution correct?

//--Update: I tried with this:

int newx = ev->pos().x(),
        newy = ev->pos().y();
if(ev->pos().x() < 0) newx = 0;
if(ev->pos().y() < 0) newy = 0;
    move(newx, newy);

It worked without crash but I'm not satisfied because of the moving is not smooth.

aviit
  • 1,957
  • 1
  • 27
  • 50
  • You might be running into an infinite loop, as `setGeometry` will trigger another call to `moveEvent`. However I just tested this code and it worked fine for me! – ajshort Dec 10 '15 at 07:01
  • thanks, I tried with `move` – aviit Dec 10 '15 at 08:23

1 Answers1

2

This should smoothly help with the upper left corner .. but you'll need to add some more conditions to get it working for all four sides.

posX and posY are member variables.

void MainWindow::moveStep() { // [SLOT]
   int movX = 0, movY = 0;
   if(posX < 0) movX = 1;
   if(posY < 0) movY = 1;
   move(posX + movX, posY + movY);
}


void MainWindow::moveEvent(QMoveEvent *ev) {

   if(ev->pos().x() < 0 || ev->pos().y() < 0) {
      posX = ev->pos().x();
      posY = ev->pos().y();
      QTimer::singleShot(10, this, SLOT(moveStep()));
   }
}

To have it even more elegantly consider using QVariantAnimation with a QRect and setGeometry().

Aaron
  • 1,181
  • 7
  • 15
  • Made an important edit. Now it really works .. the window moves smoothly back into view if moved past the left screen border. – Aaron Dec 10 '15 at 09:19
  • Consider using this mechanism to keep the window centered .. could by a nice effect .. or an annoying ; ) – Aaron Dec 10 '15 at 09:20