Qt Quick の「ステート」と「ビヘイビア」の併用
ステートとビヘイビアの併用
場合によっては、状態の変更によって生じるプロパティの変更をアニメーション化するために、ビヘイビアを使用することもあります。これは状況によってはうまく機能しますが、他の状況では予期しない動作を引き起こす可能性があります。
この問題を説明する例を以下に示します:
import QtQuick 2.0
Rectangle {
width: 400
height: 400
Rectangle {
id: coloredRect
width: 100
height: 100
anchors.centerIn: parent
color: "red"
Behavior on color {
ColorAnimation {}
}
MouseArea {
id: mouser
anchors.fill: parent
hoverEnabled: true
}
states: State {
name: "GreenState"
when: mouser.containsMouse
PropertyChanges {
target: coloredRect
color: "green"
}
}
}
}色付きの四角形にマウスを素早く繰り返し出し入れして例をテストすると、色付きの四角形は時間の経過とともに緑色に落ち着き、完全な赤色に戻ることは決してありません。これは意図した動作ではありません! この問題が発生するのは、色の変化をアニメーション化するために「Behavior」を使用している一方で、状態の変化が「MouseArea 」へのマウスの出入りによってトリガーされており、これが容易に中断されてしまうためです。
この問題をより形式的に表現すると、ステートとビヘイビアを併用すると、次のような場合に予期しない動作を引き起こす可能性があります:
- プロパティの変更をアニメーション化するために「Behavior」が使用され、特に明示的に定義された状態から暗黙のベース状態に戻る場合、および
- このBehaviorが中断され、明示的に定義された状態に(再)移行する場合。
この問題は、QMLにおけるベース状態の定義方法に起因しています。ベース状態は、明示的に定義された状態に入る直前のアプリケーションの「スナップショット」状態として定義されているからです。 この場合、緑から赤へのアニメーションの途中でアニメーションを中断して「GreenState」に戻ると、ベース状態にはアニメーション途中の中間的な状態の色が含まれてしまいます。
将来の QML バージョンでは、この状況にもっと適切に対処できるようになるはずですが、現時点では、この問題を回避するためにアプリケーションを修正するいくつかの方法があります。
1. Behavior ではなく、トランジションを使用して変更をアニメーション化する。
import QtQuick 2.0
Rectangle {
width: 400
height: 400
Rectangle {
id: coloredRect
width: 100
height: 100
anchors.centerIn: parent
color: "red"
MouseArea {
id: mouser
anchors.fill: parent
hoverEnabled: true
}
states: State {
name: "GreenState"
when: mouser.containsMouse
PropertyChanges {
target: coloredRect
color: "green"
}
}
transitions: Transition {
ColorAnimation {}
}
}
}2. 状態ではなく、条件付きバインディングを使用してプロパティの値を変更する。
import QtQuick 2.0
Rectangle {
width: 400
height: 400
Rectangle {
id: coloredRect
width: 100
height: 100
anchors.centerIn: parent
color: mouser.containsMouse ? "green" : "red"
Behavior on color {
ColorAnimation {}
}
MouseArea {
id: mouser
anchors.fill: parent
hoverEnabled: true
}
}
}3. 暗黙的なベース状態ではなく、明示的に定義された状態のみを使用する
import QtQuick 2.0
Rectangle {
width: 400
height: 400
Rectangle {
id: coloredRect
width: 100
height: 100
anchors.centerIn: parent
Behavior on color {
ColorAnimation {}
}
MouseArea {
id: mouser
anchors.fill: parent
hoverEnabled: true
}
states: [
State {
name: "GreenState"
when: mouser.containsMouse
PropertyChanges {
target: coloredRect
color: "green"
}
},
State {
name: "RedState"
when: !mouser.containsMouse
PropertyChanges {
target: coloredRect
color: "red"
}
}]
}
}© 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.