本文介绍了如何在qml中动态创建组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 QML 中动态添加组件?我参考此链接在同一窗口中单击按钮时将组件(矩形组件)添加到 main.qml 窗口中.'Ubuntu.Components' 没有安装在我的 qt 中.我不知道 JavaScript.componentCreation.js"是指这里.这是什么意思?我是 qml 的初学者.我需要知道有没有一种方法可以仅使用 qml 动态加载 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.

推荐答案

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)
      }
}

这篇关于如何在qml中动态创建组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 02:06
查看更多