views:

63

answers:

5

I have a QWidget which handles the mouseevent, i.e. it stores the mouseposition in a list when the left mouse button is pressed. The problem is, I cannot tell the widget to take only one point every x ms.

What would be the usual way to get these samples?

Edit: since the mouseevent is not called very often, is it possible to increase the rate?

+1  A: 

You have two choices. You could either put some logic in the event handler that stores the timestamp (in milliseconds) of the last event. You then check that timestamp with every event and only store the point if the proper timespan has passed.

(this is the ugly way) You could always also have a process somewhere in your app that registers the event handler every x milliseconds (if one isn't already registered) and then have your event handler un-register for the event in your handler). That way, when the event happens, the event handler gets un-registered and the timer re-registers for the event at your specified interval.

Justin Niessner
+1  A: 

You could add a single-shot QTimer that's connected to a slot that sets a boolean to true, and modify your mouse event slot to first check to make sure the bool is true, and if it is set it to false, do the code you were normally gonna do, then at the end set the single-shot QTimer to go off in x ms.

Kitsune
+1  A: 

Filter it. Just ignore all input (don't put it into list) unless x ms have passed.

QTime m_time; // member of your class
int m_interval = 100; // ms

void MyWidget::StartCapturing()
{
    m_time.start();
}

void MyWidget::OnMouseEvent(...)
{
    if(m_time.elapsed() < m_interval)
     return;

    // process event

    m_time.reset();   
}

EDIT: If by any chance you use queued connection to OnMouseEvent (if it is in different thread, unlikely in your case), use a proxy slot directly connected you interesting signal, filter inside it and only then emit signal you connect queued to. Otherwise you might spam event loop unnessesarily.

Eugene
Mouse events are not delivered with signal/slot connections, but to the virtual `QWidget::mouseEvent()` method. Your general idea is correct, though.
+2  A: 

It sounds like you don't want asynchronous event handling at all, you just want to get the location of the cursor at fixed intervals.

Set up a timer to fire every x milliseconds. Connect it to a slot which gets the value of QCursor::pos(). Use QWidget::mapFromGlobal() if you need the cursor position in coordinates local to your widget.

If you only want to do this while the left mouse button is held down, use mousePressEvent() and mouseReleaseEvent() to start/stop the timer.

Intransigent Parsnip
That's exactly what I needed. Thanks.
Burkhard
A: 

Use a timer instead of events.

tsilb