How to keep my QMainWindow always inside of the de

2019-06-23 19:39发布

问题:

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.

回答1:

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