我想在配置文件中声明一个全局属性,并在其他文件中使用它。例如,在以下位置声明mainbg
:
Style.qml :
property color mainbg: 'red'
并在其他QML文件(例如
view.qml
和main.qml
)中使用它。我该怎么做?
最佳答案
使用QML单例。
请引用this page上的“方法2”
-丑陋的QTBUG-34418注释属于我。
这些是您需要的:
Style.qml
pragma Singleton
import QtQuick 2.0
QtObject {
property color mainbg: 'red'
}
qmldir
该文件必须与单例.qml文件(在我们的示例中为
Style.qml
)位于同一文件夹中,或者您必须提供相对路径。 .qrc资源文件中可能还需要包含qmldir
。有关qmldir文件的更多信息,请参见here。# qmldir
singleton Style Style.qml
如何引用
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
}
此方法自Qt5.0起可用。即使引用同一文件夹中的QML单例,也需要一个文件夹
import
语句。如果是同一文件夹,请使用:import "."
这是我在qt-project页面上记录的错误(请参阅QTBUG-34418,单例需要显式导入才能加载qmldir文件)。
关于qt - 在其他其他QML文件的QML中声明全局属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15257946/