I'm playing around with QTest and want simulate a mouse click in my test on one of my QML elements that I have in my UI. So in other words I would like to trigger the onClicked signal handler in my QML code from C++?
This is how my QML looks like:
import QtQuick 2.0
Rectangle
{
objectName: "MessageRectangle"
width: 360
height: 360
Text
{
objectName: "MessageText"
text: qsTr("Hello World")
anchors.centerIn: parent
}
Rectangle
{
id: simplebutton
objectName: "ChangeTextButton"
color: "grey"
width: 150; height: 75
Text
{
id: buttonLabel
anchors.centerIn: parent
text: "button label"
}
MouseArea
{
id: buttonMouseArea
objectName: "ChangeTextButtonMouseArea"
anchors.fill: parent
onClicked:
{
CppApi.setMessage( "Button Clicked" );
}
}
}
}
It is a bit hard to show all the different solutions that I have tried. But I have tried to connect an own class derived from QObject with the QML item and sending click signal to it:
QObject::connect( this, SIGNAL( clicked() ), pItem, SLOT( onClicked() ) );
emit clicked();
I have also tried to call the following way:
QMetaObject::invokeMethod( pButton, "pressedChanged", Qt::DirectConnection );
Where pButton is the QQuickItem which I get when I grab the object named ChangeTextButtonMouseArea.
I have found some similar questions here. But there seems to be something different with the onClicked, somehow. If I print out all the methods that are defined in the QMetaObject that I get from the QQuickItem, then I can't find the onClicked function or the clicked signal.
This answer is somewhat in the correct direction but the the signal I want to send is not created by myself: C++ SIGNAL to QML SLOT in Qt
I also found this question: How to simulate mouse clicks in QML? But I only want to trigger a click event on a specific QML object. Do I really need to calculate the coordinates of my mouse click? Doing that seems a bit complicated since the QML items are only aware of the relative positions to their parents.
Am I trying something that is not possible? Or is the reason that I can't find any answers on the internet because the solution is so obvious?