Jonas
Jonas

Reputation: 15

How to get current mouse cursor position on QWidget?

I have to receive the current mouse cursor coordinates in mm/inch, while the cursor hovers over a QWidget. Already tried: mouseMoveEvent

void darstellung::mouseMoveEvent(QMouseEvent *event){

qDebug() << event->pos();
}

I activated the MouseTracking in the MainWindow constructor as well.

setMouseTracking(true);

It seems that the mouseMoveEvent will only return the cursor position, if the left mouse button is pressed.

Upvotes: 0

Views: 2373

Answers (1)

dhilipp
dhilipp

Reputation: 1

I have the same issue, hasMouseTracking() returns false on widget

my Workaround:

//position relative to window|       |you might add some ->parentWidget()
QPoint relPos = QCursor::pos() - this->window()->pos();

the positions are relative to virtual screen-coordinates on windows. eg: my widget is displayed at the 2nd monitor, which is left to the 1st -> that gives x=-1000 y=200 (in pixel)

check capability:

if(this->hasMouseTracking() ){
            this->setMouseTracking(true);
            qDebug("mousetracking on");
}else qDebug("\nmousetracking not available\n");

some useless hints:

https://doc.qt.io/qt-6/qwidget.html#grabMouse (this one is no good practice)

https://stackoverflow.com/a/30960032

So in your constructor you can add a line this->viewport()->setMouseTracking(true) and then override mouseMoveEvent

Upvotes: 0

Related Questions