问题描述
我目前正在尝试用不同的风格扩展我们的应用程序.对于每种样式,我都有一个单独的 qml 文件,例如颜色定义.StyleA.qml:
I am currently trying to extend our application with different style.For each style I have a separate qml file with e.g. color definitions.StyleA.qml:
import QtQuick 2.0
QtObject {
property color textColorStandard: 'black'
...
}
在我的 main.qml 中,我想根据软件属性加载正确的 qml 文件:
In my main.qml I would like to load the right qml file, based on a software property:
import QtQuick 2.0
Item {
id: mainPanel
....
Loader {
id: myDynamicStyle
source: Property.UseThemeA? "StyleA.qml" : "StyleB.qml"
}
...
Item {
id: BackGround
color: myDynamicStyle.textColorStandard
}
}
不幸的是,这种方法不起作用.有没有其他/更好的方式来完成造型?
unfortunately this approach does not work. Is there any other/better way to accomplish styling?
谢谢,迈克尔
推荐答案
使用Loader中加载的东西类型错误,我宁愿:
Using things loaded in Loader is badly typed, I would rather :
首先,为我所有的样式创建一个共同的祖先组件,例如:
First, create a common ancestor Component for all my styles, e.g :
// AbstractStyle.qml
import QtQuick 2.0;
QtObject {
property color textColorStandard;
}
接下来,派生它以创建自定义样式,例如:
Next, derivate it to create custom styles, e.g :
// StyleA.qml
import QtQuick 2.0;
AbstractStyle {
textColorStandard: "blue";
}
// StyleB.qml
import QtQuick 2.0;
AbstractStyle {
textColorStandard: "green";
}
然后在我的对象中使用一个必须使用样式的强类型属性,例如:
Then use a strongly typed property in my object that must use a style, e.g:
// main.qml
import QtQuick 2.0
Item {
id: base;
Component { id: compoStyleA; StyleA { } }
Component { id: compoStyleB; StyleB { } }
property AbstractStyle currentStyle : {
var tmp = (Property.UseThemeA ? compoStyleA : compoStyleB); // choose component
return tmp.createObject (base); // instanciate it and return it
}
Rectangle {
color: currentStyle.textColorStandard;
}
}
这样,有很多好处:
- 您的代码不使用字符串来识别组件,因此更容易发现和避免错误;
- 你不能影响一个不继承你的样式基类的项目,所以你不会遇到未定义的属性"错误,也不需要鸭子打字来确定你的样式对象中有哪些信息;
- 您没有 Loader,因此您不必遭受 Loader 内部和外部之间令人讨厌的上下文隔离";
- 所有组件将在运行时预加载,在实例化时加快速度,并让您从一开始就查看样式中是否存在语法错误,而不是仅在更改当前样式时查看;
- 最后但同样重要的是,属性自动完成将在 QtCreator 中工作,因为 IDE 将知道实际类型!
这篇关于Qt 5 样式:动态加载 qml 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!