Search code examples
qtqmlqtquick2qt-quick

Create a copy of a rectangle in QML


I want to make an area, where a small rectangles appear in the places it where clicked. Later on I would try to add an ability to move those rectangles by dragging.

After studying Help, I tried to accomplish this with a MouseArea and a Component containing a Rectangle. Then, with onClicked, I was trying to create a new copy of a Component, but I failed whatever I tried (createComponent, createObject, etc.).

What is the correct way of creating a copy of an object in this case? Am I using right tools for this goal?

MouseArea {
   Component {
      id: rect

      Rectangle {
         width: 10
         height: 10
      }
   }

   onClicked: < what? >
}

Solution

  • you can create a QML object from a string of QML using the Qt.createQmlObject() and set it's x and y values to mouseX and mouseY :

    import QtQuick 2.3
    import QtQuick.Window 2.0
    
    Window {
    
        id : root
    
        visible: true
        width: 1000
        height: 500
    
        MouseArea {
            anchors.fill: parent
    
            onClicked:{
                var newObject = Qt.createQmlObject('import QtQuick 2.3; Rectangle {color: "red"; width: 10; height: 10}',
                   root);
    
                newObject.x = mouseX;
                newObject.y = mouseY;
            }
        }
    }
    

    Also if you put the code for your rectangle in a separate qml file say myRect.qml, you can create the object from the qml file by :

    onClicked:{
         var component = Qt.createComponent("myRect.qml");
         var newObject = component.createObject(root, {"x": mouseX, "y": mouseY});
    }