[Qt-qml] Accessing C++ singleton from QML

Alex alexlordax+qt at gmail.com
Thu Oct 28 20:51:31 CEST 2010


Thanks, Bradley.  Unfortunately the architecture of my program is such
that the code which instantiates the QDeclarativeView does has no
knowledge of the object that is eventually needed on the QML side.
Think plugin architecture where the common interface is defined only
by a QML base, and any C++ back-end objects are optional (and highly
specific) for a given plugin.

Bea's suggestion works for me in this case.

Cheers,
Alex

On Thu, Oct 28, 2010 at 12:25 AM, Bradley Smith <bsmith at baysmith.com> wrote:
> If you set a context property on the rootContext of the
> QDeclarativeView, you can access public slots on the property from
> QML.
>
> C++:
>    view->rootContext()->setContextProperty("mySettings",
> Settings::instance());
>
> QML:
>    MouseArea { onClicked: { mySettings.doSomethingSlot() }  }
>
>
> On Oct 27, 12:04 pm, Alex <alexlordax... at gmail.com> wrote:
>> Hi all,
>>
>> This is probably a silly question, but how do I access a singleton
>> instance of a C++ class from QML?
>>
>> For example, I have:
>>
>> class Settings : QObject {
>> public:
>>   static Settings *instance();
>>
>> private:
>>   Settings();
>>
>> };
>>
>> In my QML code, I want to do the moral equivalent of the following:
>>
>> property variant mySettings : Settings::instance()
>>
>> What is the recommended way of doing this?
>>
>> Thanks,
>> Alex
>>
>> PS:  On a related note, I am using "variant" above because I can't
>> even qmlRegisterType the Settings class, since it doesn't have a
>> public default constructor.
>> _______________________________________________
>> Qt-qml mailing list
>> Qt-... at trolltech.comhttp://lists.trolltech.com/mailman/listinfo/qt-qml
>
> _______________________________________________
> Qt-qml mailing list
> Qt-qml at trolltech.com
> http://lists.trolltech.com/mailman/listinfo/qt-qml
>




More information about the Qt-qml mailing list