问题描述
我是一个相当大的 QML 代码库的新手,我想知道我在运行应用程序时单击的 QML 元素的属性,例如对象名称。
Qt 中的等效项是 QApplication::widgetAt()
或 QWidget::childAt()
我可以在 QMouseEvent 中调用。
我需要这些来识别用于黄瓜-cpp 步骤实现的混合 Qt/QML 应用程序中的 QML 对象,其中我已经有了 Helper::click(QString name)
。我在这里放置了一个示例项目:https://github.com/elsamuko/qml_demo
解决方法
我有一个解决方案,我可以使用。
首先,我在派生类中从 mousePressEvent
实现 QQuickView
。
然后使用 findChildren<QObject*>
对象上的 QQuickView
,我可以找到并调试 QML 对象。奇怪的是,childAt
和 children
没有列出 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
试试这个,应该可以
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 发送一个信号并找出插槽中的名称