从C++导入到qml的全局变量和qml定义变量或许有些混淆,使用下列建议或许可以解决全局变量混淆的问题。

  定义qml变量相当于定义JavaScript变量。JavaScript变量命名必须以字母,_$为开头。其他字符可以是字母,_$,数字

建议

  全局变量或外部变量可以使用$修饰变量。

例子

  • 设置导入$message变量到qml中:
...
engine.rootContext()->setContextProperty("$message", "hello world!");
...
  • qml使用:
...
Component.onCompleted: console.log($message)
...
  • 另外qml的全局变量(外部变量)也可以这样定义:
/* BaseItem.qml */
Item {
    property variant $message: "hello world!" 
    ...
}

  引用BaseItem.qml的全局变量(外部变量)$message

BaseItem {
    ...
    Component.onCompleted: console.log($message)    
    ...
}

Qt君
39 声望23 粉丝

引用和评论

0 条评论