0

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.

Jonas
  • 15
  • 2
  • Are you trying to catch these events in a mainwindow or a completely unrelated widget? – thuga Feb 24 '17 at 08:30
  • I am catching the Events in a seperate class called darstellung, related to QWidget. "class darstellung : public QWidget" @thuga – Jonas Feb 24 '17 at 08:35
  • 1
    `setMouseTracking(true)` should give you move events even when no button is pressed. Without it the widget will indeed only receive move events when a button is pressed – Kevin Krammer Feb 24 '17 at 08:43
  • I cant find the right Event in the Qt documentation for QMouseEvent, smb. knows how to handle this? – Jonas Feb 24 '17 at 08:53
  • @Jonas As Kevin said `setMouseTracking(true)` should allow you to get mouse position with `mouseMoveEvent(QMouseEvent *event)` regardless if a button is pressed or not. You can then use QScreen to get the screen dpi and convert pixels to inches – Benjamin T Feb 24 '17 at 08:57
  • 1
    You say you set mouse tracking to `true` on the mainwindow. But did you enable it for your widget? – thuga Feb 24 '17 at 09:05
  • @thuga thank you, i just forgot to relate the method to the widget: "ui->widget->setMouseTracking(true);" Now i just need to convert the output in mm/inch – Jonas Feb 24 '17 at 09:12
  • Try diving by [`QScreen::physicalDotsPerInchX`](http://doc.qt.io/qt-5/qscreen.html#physicalDotsPerInchX-prop). It will depend on each system to provide accurate information about your display. – cbuchart Feb 24 '17 at 12:38

1 Answers1

0

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

dhilipp
  • 1
  • 1