1

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Lots of types in Qt can be handled like values, i.e. you should not be manually allocating memory for them. It's the compiler's job to do it. Every single `new` in your code should have a rationale behind it. I'd guess that 9 out of 10 `new`s in SO Qt questions are unnecessary. `QPoint` is a value type! – Kuba hasn't forgotten Monica Mar 16 '18 at 20:42

1 Answers1

8

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();
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241