}
/*!
+Returns the name of \a object in this context, or an empty string if \a object
+is not named in the context. Objects are named by setContextProperty(), or by ids in
+the case of QML created contexts.
+
+If the object has multiple names, the first is returned.
+*/
+QString QDeclarativeContext::nameForObject(QObject *object) const
+{
+ Q_D(const QDeclarativeContext);
+
+ return d->data->findObjectId(object);
+}
+
+/*!
Resolves the URL \a src relative to the URL of the
containing component.
QString QDeclarativeContextData::findObjectId(const QObject *obj) const
{
- if (!idValues || !propertyNames)
+ if (!propertyNames)
return QString();
- for (int i=0; i<idValueCount; i++) {
- if (idValues[i] == obj)
- return propertyNames->findId(i);
+ for (int ii = 0; ii < idValueCount; ii++) {
+ if (idValues[ii] == obj)
+ return propertyNames->findId(ii);
+ }
+
+ if (publicContext) {
+ QDeclarativeContextPrivate *p = QDeclarativeContextPrivate::get(publicContext);
+ for (int ii = 0; ii < p->propertyValues.count(); ++ii)
+ if (p->propertyValues.at(ii) == QVariant::fromValue((QObject *)obj))
+ return propertyNames->findId(ii);
}
if (linkedContext)
void setContextProperty(const QString &, QObject *);
void setContextProperty(const QString &, const QVariant &);
+ QString nameForObject(QObject *) const;
+
QUrl resolvedUrl(const QUrl &);
void setBaseUrl(const QUrl &);
void destruction();
void idAsContextProperty();
void readOnlyContexts();
+ void nameForObject();
private:
QDeclarativeEngine engine;
delete obj;
}
+void tst_qdeclarativecontext::nameForObject()
+{
+ QObject o1;
+ QObject o2;
+ QObject o3;
+
+ QDeclarativeEngine engine;
+
+ // As a context property
+ engine.rootContext()->setContextProperty("o1", &o1);
+ engine.rootContext()->setContextProperty("o2", &o2);
+ engine.rootContext()->setContextProperty("o1_2", &o1);
+
+ QCOMPARE(engine.rootContext()->nameForObject(&o1), QString("o1"));
+ QCOMPARE(engine.rootContext()->nameForObject(&o2), QString("o2"));
+ QCOMPARE(engine.rootContext()->nameForObject(&o3), QString());
+
+ // As an id
+ QDeclarativeComponent component(&engine);
+ component.setData("import QtQuick 1.0; QtObject { id: root; property QtObject o: QtObject { id: nested } }", QUrl());
+
+ QObject *o = component.create();
+ QVERIFY(o != 0);
+
+ QCOMPARE(qmlContext(o)->nameForObject(o), QString("root"));
+ QCOMPARE(qmlContext(o)->nameForObject(qvariant_cast<QObject*>(o->property("o"))), QString("nested"));
+ QCOMPARE(qmlContext(o)->nameForObject(&o1), QString());
+
+ delete o;
+}
+
QTEST_MAIN(tst_qdeclarativecontext)
#include "tst_qdeclarativecontext.moc"