开发者

Tracking mouse cursor in QWidget

I am using the mouseMoveEvent to track the position of the mouse cursor in a simple QT app. My problem is that I want the mouseMoveEvent to fire only when the cursor is in a 400x400 QWidget. Right now it is firing no matter where the mouse is. Here is my code...

void IPA2::mouseMoveEvent(QMouseEvent * event) {
     cout << event->x() << endl;
     cout << event->y() << endl;
}

IPA2 is the name of my class. The ui was created in designe开发者_如何转开发r mode.


If I understand you correctly, you may just perform a check here like if (x,y in range) do_something.

Another way would be to create a fake widget with 400x400 dimensions and reimplement it's mouse event.

The third (probably an overkill) is to use event filters (see here).

Update:

You can't just "easily" handle the mouse events using the Qt Designer. Each .ui scheme is almost always paired up with the corresponding implementation for that scheme. This is where your handling should be done.

Qt Designer is great for automatic signal-slot handling, but mouseMoveEvent is an event and has nothing to do with the slot system.

I would say how would I implement this and you can choose (see the three possible ways before).

I would create some DummyWidget, which would have a 400x400 dimensions and custom virtual mouseMoveEvent method, which would actually handle the mouse movement.

In the constructor of my main window (which also does the .ui-based construction) I would say something like

dummy_widget_ = new DummyWidget(...);
// `dummy_widget_` is a private `DummyWidget*` member of the main window

and then probably would reposition it somewhere.

That's it - now when my main window is created, a dummy widget is added to it and every mouse movement at that widget is handled (because we've provided custom implementation).

Another moment, which is related to mouse events only: http://doc.qt.nokia.com/4.7/qwidget.html#mouseTracking-prop

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜