在 QML 中为其他 QML 文件声明全局属性 [英] declare global property in QML for other QML files
问题描述
我想在配置文件中声明一个全局属性并在其他文件中使用它.例如声明 mainbg
在:
Style.qml:
property color mainbg: 'red'
并在其他 QML 文件(如 view.qml
和 main.qml
)中使用它.我怎样才能完成这项工作?
使用 QML 单例.
请参考本页上的方法2"-- 丑陋的 QTBUG-34418 评论是我的.
这些是您需要的部分:
样式.qml
pragma Singleton导入 QtQuick 2.0QtObject {属性颜色 mainbg: '红色'}
<小时>
qmldir
此文件必须与单例 .qml 文件(在我们的示例中为 Style.qml
)位于同一文件夹中,否则您必须提供它的相对路径.qmldir
也可能需要包含在 .qrc 资源文件中.可以在此处找到有关 qmldir 文件的更多信息.
# qmldir单例样式 Style.qml
<小时>
如何参考
导入QtQuick 2.0进口 "."//从同一文件夹引用单例对象时需要这样做长方形 {color: Style.mainbg//<- 就在那里!!!宽度: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屋!