Reputation: 652
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";
}
}
Upvotes: 0
Views: 1675
Reputation: 104484
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);
Upvotes: 1