Important: Please read the Qt Code of Conduct -

QmlRegisterType and setContextProperty

  • i just wanna know when it's best to use which ?

  • Moderators

    Where you think you need it :)

    Registering a type makes it possible for you to add new QML "classes" (objects) available throughout you app. You have to instantiate them somewhere in QML code. This way you can implement some custom functionality, painting etc. in C++ and have it available in QML - in every instance you create.

    Context property exposes an already instantiated property to the QML side (a single property. You can also set context object to get e.g. new global functions). You can use that for a lot of things, but not as those "classes" mentioned above. For example, in one of my apps, I have set a "PWD" property in C++, and used it in QML to get a common base URL for relative paths.

    So, it really depends on what you want to achieve.

  • i get it now , thanks sierdzio :)

  • Moderators


    I was trying to keep it short, but if there is anything still not clear, ask. Or, even better - try in some test app.

  • well i have another question which may not be so related
    if i want to attach a certain object or property with certain qml component, for example a huge list model to be only available when an instance of the component is there, how can i do that

  • Moderators

    The usual approach on a forum is to start a new thread for every new topic. But never mind that for now, the second question is more or less related. You can request moderators to do a split, if you want to.

    Back to the question. 2 ways that immediately spring to my mind are:

    • create a casual QML file with ale the "scaffolding" for this list model (GridView, Delegate, empty (!) ListModel). Then, add a JS method (or provide C++ Invokable method) that would populate the model on the fly - when invoked (ListModel::append() is the method you need to use there), or even automatically on creation (Component.onCompleted)
    • subclass your component of choice in C++, add handling to this big data model, and add this to QML with qmlRegisterType()

  • well i understand it pretty well theoretically but don't know how it can be done in coding, if you can provide me with a little example that would be great :)
    and thanks alot :)

  • Moderators

    For the first option, an example can be found here (my second comment in that topic): "link":

    For the second one, I do not have any, you'll have to devise that yourself. A helper code may be my QWebService project, and it's QML bindings ("link":, but it would take you some time to look through that code. I suggest reading Qt docs and trying on your own.

  • i will do my best, thanks sierdzio :)

Log in to reply