结合Qt Quick Controls
File selectors 提供了一种便捷的方式来选择文件变体。Qt 提供了平台名称和区域设置作为内置选择器。Qt Quick Controls 通过应用程序当前运行的样式名称(首字母大写)扩展了内置选择器。
通过使用文件选择器,可以在不与特定样式建立硬依赖关系的情况下应用针对该样式的调整。 在可用的文件变体中,QML 引擎仅加载所选的 QML 文件。每个文件变体都可以承载上下文,即特定的样式。这通常会导致一些代码重复,但另一方面,它消除了上述对样式的硬依赖,从而使 QML 代码更加简单高效。
以下示例演示了一个自定义的圆角按钮:在Material 样式下,该按钮带有样式化的投影;而在其他样式下,则呈现为扁平化外观。文件组织方式是将CustomButton.qml 的 Material 版本放置在+Material 子目录中。
:/main.qml
:/CustomButton.qml
:/+Material/CustomButton.qml默认情况下,main.qml 会为CustomButton 类型使用CustomButton.qml 。但是,当应用程序以 Material 样式运行时,Material 选择器将生效,此时将改用+Material/CustomButton.qml 版本。
// main.qml
import QtQuick
import QtQuick.Controls
ApplicationWindow {
id: window
visible: true
CustomButton {
text: "Button"
anchors.centerIn: parent
}
}自定义按钮的基础实现是一个简单的圆角扁平按钮。
// CustomButton.qml
import QtQuick
import QtQuick.Controls
Button {
id: control
background: Rectangle {
radius: width / 2
implicitWidth: 36
implicitHeight: 36
color: control.pressed ? "#ccc" : "#eee"
}
}Material 样式中自定义按钮的实现会导入 Material 样式,请求深色主题以获得浅色文本,并为背景创建投影。
// +Material/CustomButton.qml
import QtQuick
import QtQuick.Effects
import QtQuick.Controls
import QtQuick.Controls.Material
Button {
id: control
Material.theme: Material.Dark
background: Rectangle {
implicitWidth: 48
implicitHeight: 48
color: Material.accentColor
radius: width / 2
layer.enabled: control.enabled
layer.effect: MultiEffect {
shadowEnabled: true
shadowHorizontalOffset: 3
shadowVerticalOffset: 3
shadowColor: Material.dropShadowColor
shadowBlur: control.pressed ? 0.8 : 0.4
}
}
}注意:建议 使用 `QQmlApplicationEngine`,该方法会在内部创建一个 `QQmlFileSelector ` 实例。仅需此操作即可使用 QML 文件选择器。
相关信息
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.