Simulate a pressed QML element from QTest

I play with QTest and want to simulate a mouse click in my test on one of my QML elements that I have in my user interface. So, in other words, would I like to run the onClicked signal handler in my QML code from C ++?

This is what 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 little difficult to show all the different solutions that I have tried. But I tried to associate a custom class derived from a QObject with a QML element and send it a click signal:

   QObject::connect( this, SIGNAL( clicked() ), pItem, SLOT( onClicked() ) );
   emit clicked();

I also tried calling the following path:

QMetaObject::invokeMethod( pButton, "pressedChanged", Qt::DirectConnection );

Where pButton is the QQuickItem that I get when I grab an object named ChangeTextButtonMouseArea.

. , , - onClicked. , QMetaObject, QQuickItem, onClicked .

, , , : ++ SIGNAL QML SLOT Qt

: QML? click QML. ? , QML .

-, ? , , ?

+4
1

, . , - . . , QTest, .

void ClickItem( QQuickItem* pItem, QWindow* pRootWindow )
{
   auto oPointF = pItem->mapToScene( QPoint( 0, 0 ) );
   auto oPoint = oPointF.toPoint();
   oPoint.rx() += pItem->width() / 2;
   oPoint.ry() += pItem->height() / 2;
   QTest::mouseClick( pRootWindow, Qt::LeftButton, Qt::NoModifier, oPoint );
 }
+4

All Articles