A better way to simulate a qml button click in c++?

。_饼干妹妹 提交于 2019-12-24 19:28:55

问题


My main objective is to write a test case that can simulate a qml button click from C++. The code snippet below accomplishes this but it requires a qobject_cast() from qobject to qwindow. Is there an option to implement a mouse click that takes a qobject? Is this the correct way to implement the button click or is there a better way?

main.qml file

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 file

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

private slots:
    void test_case1();

private:
    QWindow *m_window; 
...

myClass.cpp file

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:


This seems to work for me:

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

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

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


来源:https://stackoverflow.com/questions/54068360/a-better-way-to-simulate-a-qml-button-click-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!