我QTest
用来测试简单的小部件,一切都按预期工作。但是现在我有一个更复杂的测试场景,我基本上有一个小部件,它允许用户按下鼠标按钮,然后移动一些内容,然后释放鼠标按钮。
为此,我创建了以下测试工具:
主文件
#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;
}
测试对象.h
#pragma once
#include <QObject>
class TestObject : public QObject
{
Q_OBJECT
private slots:
void testCode();
};
测试对象.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));
}
因此,用户使用鼠标左键单击窗口小部件内的位置 (5,5),然后在按住按钮的同时拖动鼠标到位置 (20,20),然后在位置 (20,20) 释放按钮。
有趣的是,移动事件从未发生在小部件内部,我真的不知道为什么。
看来,我并没有完全理解它的用意QTest::mouseMove
,但是 Qt 文档在如何使用它方面也比较沉默。
如何模拟我想要的行为?