在c ++中模拟qml按钮单击的更好方法?

时间:2019-01-07 03:51:07

标签: c++ qt qml

我的主要目标是编写一个可以模拟C ++中的qml按钮单击的测试用例。下面的代码段完成了此操作,但是从qobject到qwindow都需要qobject_cast()。是否有实现使用qobject的鼠标单击的选项?这是实现按钮单击的正确方法还是有更好的方法?

main.qml文件

import QtQuick 2.11
import QtQuick.Controls 2.2
import QtQuick.VirtualKeyboard 2.2
import QtQuick.Window 2.11

ApplicationWindow {
    id: window
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Button {
        id: button
        objectName: "button"
        x: 54
        y: 118
        text: qsTr("Button")
        checkable: true
        onClicked: {
            button.text = qsTr("Clicked")
        }
    }
}

myClass.h文件

...
public:
    void ClickItem(QObject*);

private slots:
    void test_case1();

private:
    QWindow *m_window; 
...

myClass.cpp文件

void myClass::ClickItem(QObject* pItem)
{
    int x = pItem->property("x").toInt();
    int y = pItem->property("y").toInt();

    QPoint location(x,  y);
    QTest::mouseClick(m_window, Qt::LeftButton, Qt::NoModifier, location);
}

void myClass::test_case1()
{
    QObject *engine;
    QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:../app/Display.qml")));
    object = component.create();

    m_window = qobject_case<QWindow *>(object);

    QObject *item = object->findChild<QObject*>("button");
    if (item) {
        myClass::ClickItem(item);
        QVariant value = item->property("text");
        QCOMPARE(value.toString(), QString("Clicked"));
    } else {
        qDebug() << "Did not work";
    }
}

1 个答案:

答案 0 :(得分:1)

这似乎对我有用:

QObject* obj = view.findChild<QObject*>("button");

QEvent evtPress(QEvent::MouseButtonPress);
QEvent evtRelease(QEvent::MouseButtonRelease);

obj->event(&evtPress);
obj->event(&evtRelease);