Reputation: 6084
I'm using QTest
to test simple widgets and it all works as expected. But now I have a more complex test scenario, where I have basically a widget that allows the user to press the mouse button, then moves some content, and then releases the mouse button.
For this I created the following test harness:
main.cpp
#include <QtTest/QTest>
#include "TestObject.h"
int main(int argc, char** args) {
TestObject o;
QTest::qExec(&o);
}
WidgetToTest.h
#pragma once
#include <QWidget>
class WidgetToTest : public QWidget
{
Q_OBJECT
public:
WidgetToTest(QWidget* parent = nullptr);
protected:
void mousePressEvent(QMouseEvent* event) override;
void mouseMoveEvent(QMouseEvent* event) override;
void mouseReleaseEvent(QMouseEvent* event) override;
};
WidgetToTest.cpp
#include "WidgetToTest.h"
#include <QDebug>
#include <QMouseEvent>
#include <QHBoxLayout>
WidgetToTest::WidgetToTest(QWidget* parent): QWidget(parent)
{
setFixedSize(200, 200);
setLayout(new QHBoxLayout);
}
void WidgetToTest::mousePressEvent(QMouseEvent* event)
{
qDebug() << "Mouse press: " << event;
}
void WidgetToTest::mouseMoveEvent(QMouseEvent* event)
{
qDebug() << "Mouse move: "<< event; // Nothing happens here???
}
void WidgetToTest::mouseReleaseEvent(QMouseEvent* event)
{
qDebug() << "Mouse release: " << event;
}
TestObject.h
#pragma once
#include <QObject>
class TestObject : public QObject
{
Q_OBJECT
private slots:
void testCode();
};
TestObject.cpp
#include "TestObject.h"
#include "WidgetToTest.h"
#include <QTest>
#include <QApplication>
void TestObject::testCode()
{
int argc{0};
QApplication app(argc,{});
Qt::KeyboardModifiers mod;
auto w = new WidgetToTest;
w->show();
QTest::mousePress(w, Qt::MouseButton::LeftButton,mod,QPoint(5,5));
QTest::mouseMove(w, QPoint(20,20),20);
QTest::mouseRelease(w, Qt::MouseButton::LeftButton,mod, QPoint(20,20));
}
So the user clicks on position (5,5) inside the widget with the left mouse button and then drags the mouse while holding the button to position (20,20) where he releases the button at position (20,20).
Interestingly, the move event never occurs inside the widget and I really don't know why.
It seems, that I didn't fully grasped the intention of QTest::mouseMove
, but the Qt documentation is also rather taciturn in how to use it.
How can I simulate my desired behavior?
Upvotes: 3
Views: 1485
Reputation: 441
The following changes in void TestObject::testCode()
are working.
Add delay to mouse release test event otherwise the mouse move event seems to get lost/late.
auto w = new WidgetToTest;
w->setMouseTracking(true);
w->show();
QTest::mousePress(w, Qt::MouseButton::LeftButton,mod,QPoint(5,5));
QTest::mouseMove(w, QPoint(20,20),20);
QTest::mouseRelease(w, Qt::MouseButton::LeftButton,mod, QPoint(20,20),20);
Upvotes: 1