如何获取我单击的 QML 元素的 objectName?

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

我是一个相当大的 QML 代码库的新手,我想知道 运行 应用程序时我单击的 QML 元素的属性,例如objectName.

例如main.qml.

中的名称“按钮”

Qt 中的等效项是 QApplication::widgetAt()QWidget::childAt() 我可以调用 QMouseEvent。

我需要这些来识别用于 cucumber-cpp 步骤实现的混合 Qt/QML 应用程序中的 QML 对象,我已经有一个 Helper::click(QString name)。我在这里放了一个示例项目:https://github.com/elsamuko/qml_demo

试试这个,它应该有效

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")
    }
}

如果这不适合你,那么你可以从 QML 发送一个信号并找出插槽中的名称

我有一个解决方案,我可以使用。
首先,我在派生的 class.
中从 QQuickView 实现 mousePressEvent 然后在 QQuickView 对象上使用 findChildren<QObject*>,我可以找到并调试 QML 对象。奇怪的是,childAtchildren 没有列出 QML 子对象。

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 );
}

完整的项目在这里:
https://github.com/elsamuko/qml_demo