Qt World Summit: Register Today!

Unable to use "setContextObject" function twice

  • I have two classes defined in c++ , "ChargerInfo" & "BatteryInfo" which I am trying to expose to QML using contextObject

    ChargerInfo chargerInfo;
    BatteryInfo batteryInfo;

    when I call the setContextObject(&chargerInfo) function, it is working fine. But When I call the setContextObject(&batteryInfo) function second time for batteryinfo object
    I am not able to access the chargerInfo object in the QML . I am getting below error

    qrc:/main.qml:17: ReferenceError: output1 is not defined
    qrc:/main.qml:26: ReferenceError: output1 is not defined

    I am using version Qt 5.15.2 and added some part of source code below

    "ChargerInfo" class

    class ChargerInfo : public QObject{
        Q_PROPERTY(Output *output1 READ output1 WRITE setOutput1 NOTIFY output1Changed)
        Q_PROPERTY(Output *output2 READ output2 WRITE setOutput2 NOTIFY output2Changed)
        Q_PROPERTY(Output *output3 READ output3 WRITE setOutput3 NOTIFY output3Changed)

    BatteryInfo Class

    class BatteryInfo : public QObject
        Q_PROPERTY(BatteryData *bat1 READ bat1 WRITE setBat1 NOTIFY bat1Changed)
        Q_PROPERTY(BatteryData *bat2 READ bat2 WRITE setBat2 NOTIFY bat2Changed)
        Q_PROPERTY(BatteryData *bat3 READ bat3 WRITE setBat3 NOTIFY bat3Changed)

  • Moderators

    There can be only one context object. Use setContextProperty() instead, it will allow you to add as many objects as you like.

  • Thanks for the update. This is mentioned in Qt documentation , I was not able to find it

  • Lifetime Qt Champion


    While not explicitly stated in the doc, you can see everything is in singular form.

    The getter and the setter talk about "the context object".

    If it was possible to set more than one, it would have been explicitly stated and you would also likely have had an overload taking a list or vector of objects.

  • @SGaist

    Thanks for clarifying

Log in to reply