使用文件选择器Qt Quick Controls
File selectors 提供了一种选择文件变量的便捷方法。Qt XML 提供了平台名称和地域作为内置选择器。 用应用程序正在运行的样式名称(大写)扩展了内置选择器。Qt Quick Controls
通过使用文件选择器,可以应用特定于样式的调整,而不会对样式产生硬性依赖。在可用的文件变体中,QML 引擎只加载所选的 QML 文件。每个文件变体都能承担上下文,即特定的样式。这通常会导致一些代码的重复,但另一方面,也减少了上述对样式的硬性依赖,使 QML 代码更简单、更高效。
下面的示例演示了一个自定义的圆形按钮,它在Material 样式中具有风格化的下拉阴影,而在其他样式中则看起来平淡无奇。文件的组织方式是将CustomButton.qml
的 Material 版本放入+Material
子目录。
:/main.qml :/CustomButton.qml :/+Material/CustomButton.qml
默认情况下,main.qml
将使用CustomButton.qml
作为CustomButton
类型。但是,当使用 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 文件选择器所需的一切。
相关信息
© 2025 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.