在QML中为其他QML文件声明全局属性 [英] declare global property in QML for other QML files

查看:503
本文介绍了在QML中为其他QML文件声明全局属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个配置文件中声明一个全局属性,并在其他文件中使用它。例如在

Style.qml 中声明 mainbg

 属性color mainbg:'red'

并将其用于其他QML文件(如 view.qml main.qml )。我怎样才能做这件事?

解决方案

使用QML Singleton。

请参阅此页面上的方法2
- 丑陋的 QTBUG-34418 评论是我的。



这些是您需要的部分:

Style.qml

  pragma Singleton 
import QtQuick 2.0
QtObject {
property color mainbg:'red'
}






qmldir

文件必须与单例.qml文件(在我们的例子中为 Style.qml )相同的文件夹中,或者您必须给它一个相对路径。 .qrc资源文件中可能还需要包含 qmldir 。有关qmldir文件的更多信息,请参见此处

 #qmldir 
singleton风格风格.qml






如何引用

 导入QtQuick 2.0 
导入。 //当从同一个文件夹引用singleton对象时,需要这样做
Rectangle {
color:Style.mainbg //< - 那里是!
width:240;身高160
}

这种方法自Qt5.0起可用。即使在同一个文件夹中引用QML单例,也需要一个文件夹 import 语句。如果是相同的文件夹,请使用: import。这是我在qt-project页面上记录的错误(请参阅QTBUG-34418,单例需要显式导入才能加载qmldir文件)。


I want to declare a global property in a config file and use it in other files. for example declare mainbg in:

Style.qml:

property color mainbg: 'red'

and use it in other QML files (like view.qml and main.qml). How can I do this work?

解决方案

Use a QML Singleton.

Please reference "Approach 2" on this page -- The ugly QTBUG-34418 comments are mine.

These are the pieces you need:

Style.qml

pragma Singleton
import QtQuick 2.0
QtObject {
    property color mainbg: 'red'
}


qmldir

This file must be in the same folder as the singleton .qml file (Style.qml in our example) or you must give a relative path to it. qmldir may also need to be included by the .qrc resource file. More information about qmldir files can be found here.

# qmldir
singleton Style Style.qml


How to Reference

import QtQuick 2.0
import "."  // this is needed when referencing singleton object from same folder
Rectangle {
    color: Style.mainbg  // <- there it is!!!
    width: 240; height 160
}

This approach is available since Qt5.0. You need a folder import statement even if referencing the QML singleton in the same folder. If is the same folder, use: import "." This is the bug that I documented on the qt-project page (see QTBUG-34418, singletons require explicit import to load qmldir file).

这篇关于在QML中为其他QML文件声明全局属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆