【问题标题】:Create QML Component dynamically from Module从模块动态创建 QML 组件
【发布时间】:2015-08-17 23:23:09
【问题描述】:

QML 允许我们将应用程序很好地构建到模块中,然后在需要时将它们导入到我们的应用程序中。这是有道理的,特别是因为我们只需要使用命名空间而不是 URI/路径。

但是,当我想动态创建 QML 组件时,我只能从 URI / 路径加载它。例如:

var myComponent = Qt.createComponent("./qml/Button/Button.qml");

对我来说,这似乎与 Qt / QML 使用命名空间而不是 URI / 路径的理念非常矛盾。

为什么不能做到以下几点:

import QtQuick 2.4
import com.MyCustomStuff 1.0   // <-- contains my custom Button

...

function createMyObj(){
    return Qt.createComponent(Button);
}

非常感谢我们 Qt 专家的任何解释! 谢谢!

【问题讨论】:

    标签: qt qml qtquick2 qt-quick


    【解决方案1】:

    你不能这样做,因为 createComponent 只接受一个字符串,你应该使用 createObject。 使用这种方法:

    ComponentCreator.qml

        import QtQuick 2.2
    
        Item {
            id:idRoot
            // take the component that you want to create
            property Component component
    // reference to the created object, with that property you can 
    // access all properties of the created component, like I am doing in the Component.onCompleted in my main.qml 
            property Item createdObject
            function createMyObj(component){
                createdObject = component.createObject(idRoot);
            }
            onComponentChanged:{
                createMyObj(component)
            }
    
        }
    

    main.qml

    import QtQuick 2.2
    import QtQuick.Controls 1.2
    Item {
        width:800
        height: 480
        ComponentCreator{
            id:idCompCreator
            component: Button{}
        }
    Component.onCompleted: idCompCreator.createdObject.width = 100
    }
    

    【讨论】:

      【解决方案2】:

      我从来没有尝试过,因为我曾经使用过你提到的基于路径的方法,而且我现在没有笔记本电脑来测试它,但我想你可以使用上面的 import 遵循其他方法,然后定义类似Component { id: myComponent; Button { } } 的东西,从而将它与myComponent.createObject 一起使用。

      从[文档][1],createObject 确实是任何Component 的方法,所以它应该可以工作。

      无论如何,使用Qt.createComponent 的方法在我看来并不矛盾,因为它与哲学相矛盾,因为我通常将它与完全符合该哲学的qrc: 字符串一起使用,不是吗?

      如果它解决了问题,请告诉我,我晚上可以试一试,因为我一整天都在远离笔记本电脑。

      下面是一个例子:

      com.MyCustomStuff 1.0
      
      YourContainer {
          id: container
      
          // your code
      
          function createButton() {
              var bt = buttonComponent.createObject(container);
              // do whatever you want from now on :-)
          }
      
          Component {
              id: buttonComponent
              Button { }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-06-18
        • 2017-08-13
        • 2019-07-15
        • 1970-01-01
        • 2011-02-25
        • 2021-10-24
        • 1970-01-01
        • 2015-01-23
        • 1970-01-01
        相关资源
        最近更新 更多