【问题标题】:adding a class with condition using qml使用 qml 添加有条件的类
【发布时间】:2014-02-13 21:11:34
【问题描述】:

我有一个项目,我想在其中添加一个类,这取决于一个变量

import "class1"
import "class2"

Item { id: myID
property variant myVar: 0;

anchors.fill: parent;

function update() { 


     switch(myID.myVar)
     {
     case 0:        
        class1 {
             anchors.fill: parent;
        }       
        break;

    case 1:
        class2 {
             anchors.fill: parent;
        }
        break;
    }
}

}

其实这是一个错误的代码,有什么办法吗?

谢谢。

【问题讨论】:

    标签: javascript c++ qt qml


    【解决方案1】:

    QML 和 JavaScript 相互结合,但您尝试使用的是 JavaScript 上下文中的 QML 类实例化语法 - 它永远不会那样工作。加载 QML 文件后,其中定义的所有类实例都已实例化。

    您需要定义两个组件,并使用加载器动态创建其中一个。所以,像下面这样。我还没有测试过它,但我希望它能引导你朝着正确的方向前进。

    import "class1"
    import "class2"
    
    Item {
      id: myItem
      property variant myVar: 0;
      anchors.fill: parent;
    
      Component { 
        id: compClass1
        class1 {
          anchors.fill: myItem;
        }
      }       
      Component { 
        id: compClass12    
        class2 {
          anchors.fill: myItem;
        }
      } 
      Loader { id: myLoader }      
    
      function update() { 
        switch(myID.myVar) {
        case 0:
          myLoader.sourceComponent = compClass1;
          break;
        }
        case 1:
          myLoader.sourceComponent = compClass2;
          break;
        }
      }
    }
    

    【讨论】:

    • 这很有帮助!如何调用类(class1 或 class2)中的函数。我已经在类中添加了一个 ID,但是当我调用该函数时,我收到一个错误:TypeError: Result of expression 'class1ID.functionName' [undefined] is not a function。
    • 我添加了一个新问题:stackoverflow.com/questions/21787220/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 2019-03-10
    • 1970-01-01
    • 2020-03-14
    • 2021-08-26
    • 2021-04-02
    相关资源
    最近更新 更多