How to keep my QMainWindow always inside of the desktop?

青春壹個敷衍的年華 提交于 2019-12-10 17:32:57

问题


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



来源:https://stackoverflow.com/questions/34193956/how-to-keep-my-qmainwindow-always-inside-of-the-desktop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!