-1

below is my code snippet where i'm loading qml ui using dynamic object creation method now i have to implement mousearea which reside in loaded file, can anyone help me to do this

Qt.createQmlObject(" import QtQuick 2.0

     Loader {
         id: pageLoader
         source: '/HomeScreenForm.ui.qml'
         anchors.fill: parent
         anchors.rightMargin: 0
         anchors.leftMargin: 0
         anchors.bottomMargin: parent
         anchors.topMargin: parent

         }


        ", rectangle7)
Sailendra
  • 1,318
  • 14
  • 29
jay
  • 37
  • 2
  • 8
  • 1
    You can use the `Connections`-Type to connect Signals and Functions to other Signals. http://doc.qt.io/qt-5/qtqml-syntax-signals.html#using-the-connections-type For further help, a scetch-up of your loaded file would be necessary. – derM - not here for BOT dreams Nov 07 '16 at 07:09
  • 1
    What a sense to create `Loader` with `createQmlObject`? Use `Qt.createComponent` instead. – folibis Nov 07 '16 at 07:09
  • Reason for using createQmlObject is that i want to load qml file on rectangle7 and loaded file ui should be responsive @folibis – jay Nov 07 '16 at 08:37
  • 1
    `createQmlObject` is the most unefficient way of creating Qml Objects. The only reason you might want to use it is, if the code within the string is completely dynamicaly generated, and there is no way of predicting anything of the structure. e.g. if you provide a QML-Editor within your application, where the user can write his own components... If you know the string beforehand, define it as a component, an use Component.createObject() to instanciate it, or a loader. – derM - not here for BOT dreams Nov 07 '16 at 08:43
  • Yeah thank you @derM – jay Nov 07 '16 at 08:57

1 Answers1

1

Create custom item contains MouseArea. To make the area accessible from outside you can use alias, for example:

MyItem.qml

import QtQuick 2.7

Rectangle {
    id: root
    color: "yellow"
    property alias area: mouseArea

    MouseArea {
        id: mouseArea
        anchors.fill: parent
    }

    Text {
        anchors.centerIn: parent
        text: "Click me!"
    }
}

And then you can create it dynamically:

import QtQuick 2.7
import QtQuick.Window 2.0

Window {
    id: mainWindow
    width: 600
    height: 600
    visible: true

    Component.onCompleted: {
        var component = Qt.createComponent("MyItem.qml");
        if (component.status === Component.Ready) {
            var obj = component.createObject(mainWindow);
            obj.width = 200;
            obj.height = 200;
            obj.anchors.centerIn = mainWindow.contentItem;
            obj.area.onPressed.connect(
                    function(mouse){ 
                        console.log("pressed at (", mouse.x,",",mouse.y,")")
                    });
        }
    }
}

Another way is using Connections, as @derM already noticed.

BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
folibis
  • 12,048
  • 6
  • 54
  • 97