简体   繁体   中英

Qt QML C++ Plugin Singleton

Is it possible to make MyObject be always equal (one same instance) in all it's qml definitions?

C++:

class MyObject : public QObject {
        Q_OBJECT
        Q_DISABLE_COPY(MyObject)

        Q_PROPERTY(QString test READ test NOTIFY testChanged)
    public:
        explicit MyObject(QObject *parent = 0);

    signals:
        void testChanged();

    private:
        QString test() const {
            return _test;
        }

        QString _test;
};

QML:

Item {
    MyObject { id: myObject1 }
    MyObject { id: myObject2 }
}

I want myObject1 to be equal myObject2 . Some kind of singleton (but no qmlRegisterSingletonType )

I can interpret your question as if you want more than one entry of MyObject in QML code referring to the same C++ object. You also know what singleton is. How about the wrapper over the singleton that you can use with QML like:

class MyObject : public QObject {
        Q_OBJECT
        Q_DISABLE_COPY(MyObject)

        Q_PROPERTY(QString test READ test NOTIFY testChanged)
    public:
        explicit MyObject(QObject *parent = 0);

    signals:
        void testChanged();

    private:
        QString test() const {
            return MySingleton::instance().test();
        }

        // QString _test; // this supposed to be implemented in MySingleton
};

Or I in my application for many different types of communication between C++ and QML use some kind of MessageBoard from the article Exposing Attributes of C++ Types to QML . That one is even more convenient considering many uses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM