Using File Selectors with Qt Quick Controls 2
File selectors provide a convenient way of selecting file variants. Qt offers the platform name and the locale as built-in selectors. Qt Quick Controls 2 extends the built-in selectors with the name (lowercase) of the style that an application is running with.
By using file selectors, style-specific tweaks can be applied without creating a hard dependency to a style. From the available file variants, only the selected QML file is loaded by the QML engine. Each file variant can assume the context, that is, a specific style. This typically leads to some code duplication, but on the other hand, cuts the aforementioned hard dependency to the style, and leads to simpler and more efficient QML code. The same technique is used to implement the Qt Quick Controls 2 styles.
The following example demonstrates a custom rounded button that has a styled drop shadow in the Material style, and looks flat in other styles. The files are organized so that the Material version of CustomButton.qml
is placed into a +material
sub-directory.
:/main.qml :/CustomButton.qml :/+material/CustomButton.qml
By default, main.qml
will use CustomButton.qml
for the CustomButton
type. However, when the application is run with the Material style, the material
selector will be present and the +material/CustomButton.qml
version will be used instead.
// main.qml import QtQuick 2.12 import QtQuick.Controls 2.12 ApplicationWindow { id: window visible: true CustomButton { text: "Button" anchors.centerIn: parent } }
The base implementation of the custom button is a simple rounded flat button.
// CustomButton.qml import QtQuick 2.12 import QtQuick.Controls 2.12 Button { id: control background: Rectangle { radius: width / 2 implicitWidth: 36 implicitHeight: 36 color: control.pressed ? "#ccc" : "#eee" } }
The Material style's implementation of the custom button imports the Material style, requests a dark theme to get light text, and creates a drop shadow for the background.
// +material/CustomButton.qml import QtQuick 2.12 import QtGraphicalEffects 1.12 import QtQuick.Controls 2.12 import QtQuick.Controls.Material 2.12 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: DropShadow { verticalOffset: 1 color: Material.dropShadowColor samples: control.pressed ? 20 : 10 spread: 0.5 } } }
Note: It is recommended to use QQmlApplicationEngine, which internally creates a QQmlFileSelector instance. This is all that is needed to take QML file selectors into use.
Related Information
© The Qt Company Ltd
Licensed under the GNU Free Documentation License, Version 1.3.
https://doc.qt.io/qt-5.12/qtquickcontrols2-fileselectors.html