QML: How to access a singleton in another singleton



  • The context is very common in C++, for example, I have two classes A and B, and I want to invoke a static method of A within a static method of B:

    class A
    {
    public:
        static void methodA() {}
    };
    
    class B
    {
    public:
        static void methodB()
        {
            A::methodA();
        }
    };
    

    In qml, I simplify the code like these:
    qmldir

    singleton Singleton1 Singleton1.qml
    singleton Singleton2 Singleton2.qml
    

    Singleton1.qml

    pragma Singleton
    import QtQuick 2.0
    QtObject {
        function method1() {
            console.log("invoke method1");
        }
    }
    

    Singleton2.qml

    pragma Singleton
    import QtQuick 2.0
    QtObject {
        function method2() {
            Singleton1.method1();
        }
    }
    

    When I invoke method2 in Singleton2, something gose wrong:

    qrc:/Singleton2.qml:5: ReferenceError: Singleton1 is not defined
    

    After googling, I add import "." to Singleton2.qml, then everything works fine until I add import "." to Singleton1.qml. It seems that if more than one singleton file uses import ".", the application will crash immediately (bug?) without any useful error information but only these:

    xxx.exe exited with code -1
    

    So, what's the correct way to access a singleton in another singleton?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.