Simulating mouse events - properly [Solved]
-
For a simple automated application test, I need to simulate some mouse events. Basically, just a 'click' (down+up).
Here's the code I have come up with so far. It works quite well, but not under certain circumstances (more on that below):
@QMouseEvent* CTcmg_TestHelpers::createMouseEvent(const QWidget* const pWidget,
const QEvent::Type eventType,
const QPoint& widgetPos,
const Qt::MouseButton buttons,
const Qt::KeyboardModifiers modifiers,
Qt::MouseButton buttonCausingEvent)
{
if (pWidget == NULL)
{
return NULL;
}QMouseEvent* pEvent = new QMouseEvent(eventType, widgetPos, pWidget->mapToGlobal(widgetPos), buttonCausingEvent, buttons, modifiers); return pEvent;
}
void CTcmg_TestHelpers::simulateMouseClick(QWidget* const pWidget,
const QPoint& widgetPos,
const Qt::MouseButton button,
const Qt::KeyboardModifier modifiers)
{
if (pWidget == NULL)
{
return;
}if (QApplication::instance() == NULL) { return; } QMouseEvent* pDown = createMouseEvent(pWidget, QEvent::MouseButtonPress, widgetPos, button, modifiers, button); QMouseEvent* pUp = createMouseEvent(pWidget, QEvent::GraphicsSceneMouseRelease, widgetPos, Qt::NoButton, modifiers, button); (void) QApplication::instance()->sendEvent(pWidget, pDown); QApplication::processEvents(); (void) QApplication::instance()->sendEvent(pWidget, pUp); QApplication::processEvents();
}
@It doesn't property work with QGraphicsView. It seems that the mouse event normally arrives in QGraphicsView via an event filter. For the simulated event, the event filter is not triggered.
I took a look into Qt's source code, and noticed that upon a 'real' mouse click, QApplicationPrivate::sendMouseEvent is called which does a few extra things specific to mouse events.
Sending the event via sendEvent completely bypasses these logics. QApplication::sendEvent calls QApplication::notify, and the documentation on notify implies that mouse events are correctly delivered. How can that be, if sendMouseEvent is bypassed?Do you know a better way to simulate mouse clicks, or have any idea what I might try to make the simulated mouse events behave just like real ones?
-
Stupid Copy & Paste error. See GraphicsSceneMouseRelease in my code. Should be MouseReleaseEvent