Search code examples
qtqmlqtquick2

How to put multiple singletons in one qmldir file?


I want to use multiple singletons in one qmldir file but it doesn't seem to work, I don't have an error but the program doesn't launch.

qmldir:

singleton File1 1.0 File.qml
singleton File2 1.0 File2.qml

main:

import QtQuick 2.7
import QtQuick.Controls 2.1

Window {
    visible: true
    width: 640
    height: 480
    title: qstr("hello world!")

    Button {    
        onCliked: File2.test();
    }
}

File2.qml:

pragma Singleton
import QtQuick 2.7
Item {
    signal test;
    onTest: console.log("File2 received signal");
}

File1.qml:

pragma Singleton
import QtQuick 2.7
Item {
    signal test;
    onTest: console.log("File1 received signal");
}

The code works if I delete the second line in qmldir, but then File2 will be undefined.


Solution

  • If your qmldir file is exactly as you have written:

    Singleton File1 1.0 File.qml
    Singleton File2 1.0 File2.qml
    

    The error might reside within that, as the keyword is singleton, not Singleton.

    Try that:

    singleton File1 1.0 File.qml
    singleton File2 1.0 File2.qml
    

    But that error should not fail silently. There should be some errors:

    [main.qml] a component declaration requires two or three arguments, but 4 were provided
    [qmldir] a component declaration requires two or three arguments, but 4 were provided

    main.qml:

    import QtQuick 2.7
    import QtQuick.Controls 2.0
    import '.'
    
    ApplicationWindow {
        id: window    
        width: 800
        height: 600
        visible: true    
        Row {
            spacing: 3
            Button {
                text: 'single1'
                onClicked: Single.sig()
            }
    
            Button {
                text: 'signle2'
                onClicked: Single2.sig()
            }
        }    
    }
    

    singleton.qml

    pragma Singleton
    import QtQuick 2.0
    QtObject {
        signal sig
        onSig: console.log('Singleton1 Received')
    }
    

    singleton2.qml

    pragma Singleton
    import QtQuick 2.0
    QtObject {
        signal sig
        onSig: console.log('Singelton2 Received')
    }
    

    qmldir

    singleton Single 1.0 singleton.qml
    singleton Single2 1.0 singleton2.qml
    

    Works like a charm.