我有一個QML對象,它可以在其中創建相同的對象。函數addChildRect從C++中調用。每個對象都提供有其獨特的id
和objectName
(對於每個對象它們都是相同的)。我想使用QObject::findChild
,從C++訪問它們,但對於動態創建的對象,此函數總是返回空指針。我的建議是,該函數只解析最初在QML中的對象。我怎樣才能訪問從C++動態創建的對象?從C++訪問動態創建的QML對象
Rect.qml
Rectangle {
color: "red"
function addChildRect(id,x,y,width,height)
{
var component;
component = Qt.createComponent("Rect.qml");
component.createObject(this, {
id:id,
objectName:id,
x:x,
y:y,
width:width,
height:height});
}
}
C++代碼:
//find element
auto parentRectView = engine.rootObjects().first()->findChild<QObject*>(QString::number(id()));
//create element
QMetaObject::invokeMethod(parentRectView,"addChildRect",
Q_ARG(QVariant,id()),
Q_ARG(QVariant,m_position.x()),
Q_ARG(QVariant,m_position.y()),
Q_ARG(QVariant,m_size.height()),
Q_ARG(QVariant,m_size.width()));
我想你應該爲動態創建的對象設置父對象來查找是否使用'QObject :: findChild'。此外,爲了避免不必要的操作,您可以將指向從addChildRect創建的對象的指針返回給C++ – folibis
@folibis感謝您的回答?我是否正確理解你,我應該在QML對象構造代碼中添加'parent:this'? 也可以請你提供一個簡單的例子,如何從QML返回指針? – Lecko
查看我的回答下面 – folibis