我有Theme1.js,其中包含与Theme 1样式相关的属性变量,类似于主题2,Theme2.js 现在在main.qml中,如果我单击MouseArea,主题应该在Theme1和Theme2之间切换。我发现QML中不存在条件导入语句。还有其他办法吗?
Theme1.js
var color="red";
var textString="This is Theme1"
Theme2.js
var color="green";
var textString="This is Theme2"
main.qml
import QtQuick 2.3
import QtQuick.Window 2.2
import "Theme1.js" as Theme //default Theme
Window {
visible: true
color:Theme.color
MouseArea {
anchors.fill: parent
onClicked: {
//Change Theme 1 to Theme 2. Basically Toggle Theme here
}
}
Text {
text: Theme.textString
anchors.centerIn: parent
}
}
答案 0 :(得分:4)
首先,建议不要使用js
- 库来存储值,稍后您将绑定。 This is as it is not advised to bind to var
-types。您应该考虑将您的库转换为QtObject
- 单例。
仅将库用作函数库。
要更改主题,您可能只有一个单身Style
pragma Singleton
import QtQuick 2.0
QtObject {
property Theme current: theme1
property Theme theme1: Theme1 { }
property Theme theme2: Theme2 { }
}
Theme.qml 类似于:
import QtQuick 2.0
QtObject {
property color color0
property color color1
property color colorX
}
然后 Theme1.qml
import QtQuick 2.0
Theme {
color0: 'green'
color1: 'blue'
colorX: 'red'
}
和 Theme2.qml :
import QtQuick 2.0
Theme {
color0: 'red'
color1: 'pruple'
colorX: 'yellow'
}
然后将属性绑定到color: Style.current.colorX
要更改样式,请将另一个主题指定给Style.current
编辑: 使用中间变量来缩短值的路径可能是一种优化。它增加了不需要使用Style.current.color0
但至少使用Style.color0
的便利性。
您可以将此用作 Style.qml
pragma Singleton
import QtQuick 2.0
Theme { // Use Theme instead of QtObject
property Theme current: theme1
property Theme theme1: Theme1 { }
property Theme theme2: Theme2 { }
// Bind the `Theme`s properties as intermediate variables to the current Theme.
color0: (current && current.color0 ? current.color0 : 'defaultColor0')
color1: (current && current.color1 ? current.color1 : 'defaultColor1')
colorX: (current && current.colorX ? current.colorX : 'defaultColorX')
}