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();
}