How do I get the objectName of QML elements I click on?

1k views Asked by At

I'm new in a rather large QML codebase and I want to know the properties of the QML element I click on when running the application, e.g. objectName.

E.g. the name "button" in this main.qml.

The equivalent in Qt is QApplication::widgetAt() or QWidget::childAt() I can call in a QMouseEvent.

I need these to identify QML objects within a mixed Qt/QML application for cucumber-cpp step implementations, where I already have a Helper::click(QString name). I put up an example project here: https://github.com/elsamuko/qml_demo

2

There are 2 answers

1
elsamuko On BEST ANSWER

I have a solution, I can work with.
First I implement mousePressEvent from QQuickView in a derived class.
Then with findChildren<QObject*> on the QQuickView object, I can find and debug the QML objects. Strangely, childAt and children do not list the QML child objects.

void ClickView::mousePressEvent( QMouseEvent* ev ) {

    QObjectList children = this->findChildren<QObject*>( QRegularExpression( ".+" ) );

    for( QObject* child : children ) {

        // only search for QML types
        if( !strstr( child->metaObject()->className(), "_QMLTYPE_" ) ) { continue; }

        QVariant vX = child->property( "x" );
        QVariant vY = child->property( "y" );
        QVariant vW = child->property( "width" );
        QVariant vH = child->property( "height" );

        if( vX.isValid() && vY.isValid() && vW.isValid() && vH.isValid() ) {
            QRect rect( vX.toInt(), vY.toInt(), vW.toInt(), vH.toInt() );

            if( rect.contains( ev->pos() ) ) {
                qDebug() << child;
            }
        }
    }

    QQuickView::mousePressEvent( ev );
}

The complete project is here:
https://github.com/elsamuko/qml_demo

6
Vahagn Avagyan On

try this, it should work

Rectangle {
    id: item
    signal qmlSignal(msg: string)
    objectName: "rectangle"

    MouseArea {
        anchors.fill: parent
        onClicked: item.qmlSignal("rectangle clicked")
        onDoubleClicked: item.qmlSignal("rectangle double clicked")
        onEntered: item.qmlSignal("mouse entered the rectangle")
        onExited: item.qmlSignal("mouse left the rectangle")
    }
}

if this does not suit you, then you can send a signal from the QML and find out the name in the slot

How to connect a QML signal with a C++ slot?