当前位置: 代码迷 >> 综合 >> 【QML】C++端访问QML的子对象/子节点
  详细解决方案

【QML】C++端访问QML的子对象/子节点

热度:7   发布时间:2023-10-21 01:39:14.0

QML程序:

Item {id:rootwidth: 800height: 480SwipeView {id: swipeViewcurrentIndex: 0anchors.fill: parentPage_7AnalogReaderChart {id: page_7AnalogReaderChart}}}

通常QML是通过 QQuickWidget注册到C++端实现实例化,通过

(QObject *)ui->quickWidget->rootObject();

只能获取根节点,如何获取子节点 page_7AnalogReaderChart ?

首先,C++只能通过objectName 来访问,所以QML端必须加上objectName :

Item {id:rootwidth: 800height: 480SwipeView {id: swipeViewobjectName: "swipeView1"currentIndex: 0anchors.fill: parentPage_7AnalogReaderChart {id: page_7AnalogReaderChartobjectName: "page_7AnalogReaderChart1"}}
}

C++端:

(QObject *)ui->quickWidget->rootObject()->findChild<QObject *>("page_7AnalogReaderChart1")

显然这是可以跨越多个层次发现子节点,非常方便。

  相关解决方案