Qt Quick コントロールでのファイルセレクタの使用
File selectors は、ファイルのバリエーションを選択するための便利な手段を提供します。Qtは、プラットフォーム名とロケールを組み込みのセレクタとして提供しています。「Qt Quick 」コントロールは、アプリケーションが実行されているスタイルの名前(大文字)を、組み込みのセレクタに追加します。
ファイルセレクタを使用することで、スタイルへの強固な依存関係を作り出すことなく、スタイル固有の調整を適用することができます。 利用可能なファイルバリアントの中から、選択された 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
}
}
}注: 内部でQQmlFileSelector インスタンスを作成するQQmlApplicationEngine の使用を推奨します 。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.