简体   繁体   中英

Is there any better way to move a window?

I am working on an application with Qt Framework for desktop. Since I remove every window decoration I had to implement the main window to receive move event from when the user click on it and move the mouse around.

I tried the following code but I am not satisfied. I wonder if there is any better way to this with more elegance.

QPoint* mouseOffset; //global variable that hold distance of the cursor from 
                       the top left corner of the window.

void ArianaApplication::mouseMoveEvent(QMouseEvent* event)
{
     move(event->screenPos().x() - mouseOffset->x(),
          event->screenPos().y() - mouseOffset->y());
}

void ArianaApplication::mousePressEvent(QMouseEvent*)
{
     mouseOffset = new QPoint(QCursor::pos().x() - pos().x(),
                              QCursor::pos().y() - pos().y());
}

Would you suggest me something else?

The method is correct, but the implementation can be improved in the following points:

  • mouseOffset is not necessary to be a pointer, since you are creating dynamic memory unnecessarily and you have the responsibility to eliminate it.

  • It is not necessary to obtain each component, QPoint supports subtraction .

*.h

QPoint mouseOffset;

*.cpp

void ArianaApplication::mouseMoveEvent(QMouseEvent * event)
{
     move(event->globalPos() - mouseOffset);
}

void ArianaApplication::mousePressEvent(QMouseEvent * event)
{
     mouseOffset = event->globalPos() - frameGeometry().topLeft();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM