Forcing a state cycle
-
I wrote this simple QML element in Qt 6.2.0:
import QtQuick Text { id: root property string value: "" property color textColor: "white" property int posX: 0 property int posY: 0 property int size: 50 property int time: time opacity: 0.0 text: value color: textColor y: posX x: posY font.pixelSize: size rotation: -90 horizontalAlignment: Qt.AlignHCenter verticalAlignment: Qt.AlignVCenter state: "off" states: [ State { name: "on"; PropertyChanges { target: root; opacity: 1.0 } }, State { name: "off"; PropertyChanges { target: root; opacity: 0.0 } } ] transitions: Transition { NumberAnimation { properties: "opacity"; easing.type: Easing.Linear; duration: 500 } } function show() { timer.restart() state = "on" } Timer { id: timer running: false repeat: false interval: root.time * 1000 onTriggered: root.state = "off" } }
Here an usage example:
OverlayText { id: ovText } function textChanged(value, color, time, position, size) { ovText.value = value ovText.color = color ovText.time = time ovText.posX = position.x ovText.posY = position.y ovText.size = size ovText.show() }
It works in this way:
- when
textChanged
is called, it sets theOverlayText
properties and begins the animation to show the text - when the time expires, it begins the animation to hide the text
The problem is: if
textChanged
is called before the previous timer has expired, there are no transitions becauseOverlayText
is still in state "on".The expected behavior is:
- if timer is still active (or state is still "on" which is the same)
- stop the timer, go to state "off"
- change the properties
- come back to state "on"
I understand I can do this with some functions and variables, but I wonder if there is a more QML-way to do this.
- when
-
ToolTip has some of this functionality built in.
I would try making the default state of empty. Don't set it. Set initial opacity of root to 0.0 (which you have). Set the "when" property of your "on" state to timer.running. So when you set "on" state the timer is running. When it finishes it should shut off running and take you out of "on" state to default state.
You might be able to tie the "on" state solely to the timer.running on the when clause. So you never set the state to "on".
Not quite sure how to trigger what you want with textChanged. Maybe another timer. Seems messy.
-
Maybe need another intermediate state for the fade and and in. You can fire scripts in response to state change: https://doc.qt.io/qt-5/qml-qtquick-statechangescript.html
-
Or don't use states at all.
use a Behavior or just start an SequentialAnimation manually when the text changes.