How can serveral same qml objects references to one C++ object?



  • Hi together,

    I have a question about instantiating several qml objects but only references to one C++ object.
    I have written a C++ object for displaying a webcam using openCV. I have successfully registered the C++ object and I'm able to embed it in qml.

    My C++ application (using QDeclativeView) uses QML as it's UI. The UI is a flickable one and you can switch between several pages. Some pages embeds the C++ object.

    The problem: Every embedded C++ object has its own C++ instance!

    I want to have that every embedded C++ object references only to one C++ instance.

    Example:

    test.qml:

    Row {
    spacing: 5

    MyCamera {
    id: camera1
    with: 100
    height: 100
    number: 0
    }

    MyCamera {
    id: camera2
    with: 100
    height: 100
    number: 0
    }
    }

    Result:
    The constructor of the C++ class is called twice.

    What I want:
    Camera1 and Camera2 references to one C++ instance.

    Why?
    My "logical layer" which instantiates the C++ object "paints" something into the one and only camera widget. And "Camera1" and "Camera2" should be displaying it.

    Thx
    jackmack



  • You create two MyCamera items. The qml engine instantiates the items. So there are two C++ instances of your QQuickItem subclass.

    You can add your "logical layer" to the qml context through the qml view so the qml items can interact with its properties.


  • Moderators

    This is how QML works. Every component you declare is a separate instance.

    You could experiment with transforming your class into a singleton, or you can instantiate the component in C++ and passing instances to GUI, or maybe a clever use of Loader could help:
    @
    MyCamera {
    id: globalCamObject
    }

    Loader {
    id: camera1
    sourceComponent: globalCamObject
    }

    Loader {
    id: camera2
    sourceComponent: globalCamObject
    }
    @


Log in to reply
 

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