Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

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

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

question from:https://stackoverflow.com/questions/65935757/how-do-i-get-the-objectname-of-qml-elements-i-click-on

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...