Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

javascript - how to create components dynamically in qml

How to dynamically add components in QML? I refered this link to add a component(Rectangle component) into main.qml window upon a button click in same window. 'Ubuntu.Components' is not installed in my qt. I don't know javascript. "componentCreation.js"is refered here. What does it means? i am beginner in qml . i need to know is there a way to load qml comonents dynamically by using qml only.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

main.qml

import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    id:appWindow
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    property int count: 0
    signal forward
    function fun1(argument1){
     console.log("A function fun1()in the main QML file is invoked by dynmic object")
     console.log("Returned parameter from the QML dynamic objects = ", argument1)
     }

    Item {
        id: root
        width: parent.width
        height: parent.width
        function createItem() {
            Qt.createQmlObject("import QtQuick 2.5; Rectangle { x: 100; y: 100; width: 100; height: 100; color: "blue" }", root, "dynamicItem");
        }
    }

    Button{
        width: 200
        height: 50
        text:"Click Me"
        y:400
        x:350
        onClicked: {
            count++
            if(count==1)
            Qt.createComponent("Sprite.qml").createObject(appWindow, {"x": 100, "y": 100});
            if(count===2){
                appWindow.forward()
            }
       }
   }
   onForward:console.log("forward signal is emitted in main QML")
}

Sprite.qml

import QtQuick 2.0

Rectangle {
    id:idRect
    signal buttonClicked()
    width: 80;
    height: 50;
    color: "red";
    x:10;
    y:100
    property string fromCallee:'This value is send signal argument'
    signal send(string pass);
    MouseArea {
                  id: leftMouseArea
                  anchors.fill: parent
                  onClicked:idRect.buttonClicked()
              }
     Component.onCompleted:{
     forward.connect(fun2);
     send.connect(fun1);
     send(fromCallee);
     }
      function fun2(){
          console.log('signal received at dynamic object')
          console.log("value of main qml property 'count'="+count)
      }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...