[英]Interacting with delegated QML Component in Repeater from C++
我無法從C ++訪問Repeater中的委托QML組件。 請在下面找到代碼。 謝謝。
main.cpp中
#include <QApplication>
#include <QDebug>
#include <QQuickView>
#include <QQuickItem>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QQuickView view;
view.setSource(QUrl(QStringLiteral("qrc:/Main.qml")));
view.show();
QQuickItem *object = view.rootObject();
QObject *rectangle = object->findChild<QObject*>("rect1");
if (!rectangle)
qDebug() << "MyError: rectangle was not found";
app.exec();
}
Main.qml
import QtQuick 2.4
Row {
Repeater {
model: 3
Rectangle {
width: 50; height: 50
color: index %2 ? "black" : "white"
objectName: "rect" + index
}
}
}
控制台輸出:
MyError: rectangle was not found
我已經在C ++中實現了自己的遞歸函數模板'findChild'函數。
template <class T>
SearchType findChild(QQuickItem* object, const QString& objectName)
{
QList<QQuickItem*> children = object->childItems();
foreach (QQuickItem* item, children)
{
if (QQmlProperty::read(item, "objectName").toString() == objectName)
return item;
T child = findChild<QQuickItem*>(item, objectName);
if (child)
return child;
}
return nullptr;
}
並將其稱為默認函數。
QQuickItem *object = view.rootObject();
QQuickItem *rectangle = findChild<QQuickItem*>(object, "rect1");
if (rectangle)
{
qDebug() << rectangle;
qDebug() << rectangle->objectName();
}
並獲得輸出:
QQuickRectangle(0x2222b40, name="rect1", parent=0x22245b0, geometry=50,0 50x50)
"rect1"
如果調用object->dumpObjectTree()
,將看到類似以下控制台輸出的內容:
QQuickRow::
QQuickRepeater::
QQmlComponent::
如您所見,對象樹不包含作為專用qobject的矩形。 在我對QML方面的有限理解中,有一棵包含所有可見qml項/組件的樹。 您至少可以通過qml中的“兒童”屬性來訪問這些內容。 為了顯示這一點,我將您的qml文件更改為:
Main.qml:
Row {
id: row
Repeater {
model: 3
Rectangle {
width: 50; height: 50
color: index %2 ? "black" : "white"
objectName: "rect" + index
}
}
Component.onCompleted: {
console.log(row.children[0].objectName);
console.log(row.children[1].objectName);
console.log(row.children[2].objectName);
}
}
輸出結果如下:
qml: rect0
qml: rect1
qml: rect2
MyError: rectangle was not found
當然,直接可訪問性和索引取決於您的其他項目/組件。 從這里開始,您可以編寫自己的遞歸'findChild'函數並將結果對象公開給C ++。 此處描述方式: http : //doc.qt.io/qt-5/qtqml-cppintegration-interactqmlfromcpp.html
例如,您可以像這樣在qml中實現“ findChild”:
function findChild(propertyName, propertyValue) {
return findChildRecursivly(row, propertyName, propertyValue)
}
您可以從C ++調用此qml函數,例如
QVariant result;
QMetaObject::invokeMethod(object, "findChild",
Q_RETURN_ARG(QVariant, result),
Q_ARG(QVariant, "objectName"),
Q_ARG(QVariant, "rect1"));
rectangle = result.value<QObject *>();
使用以下附加代碼行:
if (!rectangle)
{
qDebug() << "MyError: rectangle was not found";
}
else
{
qDebug() << rectangle;
qDebug() << rectangle->objectName();
}
您得到以下輸出:
QQuickRectangle(0x1c1beef, name = "rect1")
"rect1"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.