[Development] Namespacing QML context properties

Alan Alpert 416365416c at gmail.com
Sun Dec 8 23:54:04 CET 2013

On Sun, Dec 8, 2013 at 5:38 AM, Alberto Mardegan
<mardy at users.sourceforge.net> wrote:
> Hi all!
>   One of the issues that has most bothered me when developing in QML is
> dealing with the same variable name in item properties and context
> properties. For example:
> // "model" is a context property
> Loader {
>     property variant model: model
>     sourceComponent: someComponent
> }
> The code above will not work. And I cannot find a way to make the
> "model" context property available to the loader source component. For
> reference:
> http://qt-project.org/doc/qt-5.0/qtquick/qml-qtquick2-loader.html#using-a-loader-within-a-view-delegate
> See especially the last code snippet there. Notice how the variable name
> had to be changed from "index" to "modelIndex", in order to workaround
> the issue I described above.
> However, renaming properties is not always desirable.
> Are there some tricks I'm not aware of? If not, what about introducing a
> reserved word (maybe "qmlContext"), and let it refer to the current context?
> So, one could write qmlContext.variableName to avoid ambiguity with
> properties names "variableName", and my example above would change like
> this:

What do you mean "current context"? The problem you seem to be hitting
is that there is another symbol in the current context that you want
to avoid, so that it finds a symbol higher up the tree. That would
mean something like engine.rootContext(), but I don't think that would
make sense in QML.

> Loader {
>     property variant model: qmlContext.model
>     sourceComponent: someComponent
> }
> Thoughts?

Context properties are there as a light-weight option for applications
- i.e. for cases where you don't mind renaming, or giving long names
like pleaseDontConflictModel. For a reliable API with good naming, you
should be using a singleton API instead of context properties.

The history is that context properties arrived in Qt 4 and singleton
APIs arrived in Qt 5 as a better approach (albeit with some
differences that make automated porting impossible). If we had
singleton APIs to start with, we probably wouldn't have provided
context properties at all. If it weren't for the convenience context
properties offer, I'd recommend all context property usage be migrated
to use singleton APIs. As it is, I only recommend that for all module
APIs (basically, if you used setContextProperty inside
initializeEngine you should probably use singleton APIs now instead).

Alan Alpert

More information about the Development mailing list