Qt Quick Controls 2的目标之一是将控件的逻辑与外观分离。外观的实现由QML代码和图形资源组成。使用Imagine样式(imagine style),可以自定义应用程序的外观和图形资源
Imagine样式基于图像资源。样式带有一组默认的图像,可以通过自定义命名指定提供包含图像的目录,从而更改界面外观。
示例
import QtQuick 2.14
import QtQuick.Controls 2.5
ApplicationWindow {
id:mainwin
visible: true
width: 640
height: 480
title: qsTr("imagine style")
Column {
anchors.top:parent.top
anchors.left: parent.left
anchors.margins: 10
width: mainwin.width/2
spacing: 10
Repeater {
model: 5
Button {
text: qsTr("click")
width: parent.width
height: mainwin.height/6
}
}
}
Grid {
anchors.top: parent.top
anchors.right: parent.right
anchors.margins: 10
spacing: 10
columns: 2
Repeater {
model: 10
Button {
text: qsTr("check")
height: mainwin.height/6
checkable: true
}
}
}
}
上述代码的显示效果是这样的
界面很平常,所以就需要使用imagine style美化一下,imagine style的默认效果如下
也可以添加imagine style的资源,添加资源之后,整体目录结构如下
其中,qtquickcontrols2.conf的内容如下
[Controls]
Style=Imagine
[Imagine]
Path=:images/imagine
前两行表示空间的风格,后两行表示imagine style的UI资源路径
UI资源中的图片命名也是有讲究的
首先看后缀,有png和9.png两种,9.png是安卓开发里面的一种特殊的图片,这种格式的图片通过ADT自带的编辑工具生成,使用九宫格切分的方法,使图片可以自适应显示。
图片的命名按照如下格式命名
<control>-<element>-<states>
<control>表示空间,<element>表示空间中的元素,这两个是必需的,<states>表示的是空间的状态,是可选的。例如,为button提供了一个名为“button background.9.png”的文件,它将用于设置button的background属性并支持button的每个状态。而"button background-pressed.9.png"表示用于设置button的background属性,但是只支持button的press状态(也就是说,只有pressed状态出现时(button被按下),才会使用该图片)
常用的状态有以下九个
disabled
pressed
checked
checkable
focused
highlighted
flat
mirrored
hovered
添加资源后的效果如下
参考
《qml book》
https://doc.qt.io/qt-5/qtquickcontrols2-imagine.html
https://baike.baidu.com/item/.9.png/5404360
欢迎大家评论交流,作者水平有限,如有错误,欢迎指出