簡體   English   中英

動畫 QML 按鈕組件

[英]Animate QML Button component

main.qml

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick 2.0
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.1
import QtQuick.Controls 2.1
import QtGraphicalEffects 1.0

Window 
{
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    TT
    {
        MouseArea
        {
            anchors.fill: parent
            onClicked:
            {
                parent.buttonPressed = true
            }
        }
    }
}

TT.qml

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick 2.0
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.1
import QtQuick.Controls 2.1
import QtGraphicalEffects 1.0


Rectangle
{
    id:ll
    height: 20; width: 100

    property bool buttonPressed: false

    Button
    {
        id: redRect
        background: Rectangle
                    {
                        height: 20; width: 100
                        color: "red"
                        border.width: 2
                    }

        anchors.fill: parent

        states: State {
                name: "pressed"; when: ll.buttonPressed
                PropertyChanges { target: redRect; scale: 1.2 ; }
            }

        transitions: Transition
        {
            NumberAnimation { properties: "scale"; duration: 200; easing.type: Easing.InOutQuad }
        }
    }
}

我想通過main.qml為按鈕設置動畫。
當我寫buttonPressed = true時,問題是它始終保持真實。

我應該在哪里將其設置為 false 以便當我再次單擊時它再次動畫?

@splaytreez 的回答有效,他建議擺脫您的buttonPressed屬性和無關的MouseArea是正確的。 我想提供一個替代解決方案,因為隨着代碼的增長和變得更加復雜,我經常發現狀態和轉換難以遵循。 更直接的方法是創建 animation 對象並直接調用它們。

    Button {
        id: redRect
        onPressed: anim.start()

        SequentialAnimation {
            id: anim

            // Expand the button
            PropertyAnimation {
                target: redRect
                property: "scale"
                to: 1.2
                duration: 200
                easing.type: Easing.InOutQuad
            }

            // Shrink back to normal
            PropertyAnimation {
                target: redRect
                property: "scale"
                to: 1.0
                duration: 200
                easing.type: Easing.InOutQuad
            }
        }
    }

Transition有一個屬性running 你可以嘗試這樣的事情:

transitions: Transition
{
    NumberAnimation { 
        properties: "scale";
        duration: 200; 
        easing.type: Easing.InOutQuad
    }

    onRunningChanged: {
        if (!running) buttonPressed = false;
    }
}

現在,你真的需要這個屬性嗎? 您是否考慮過使用onPressed信號:

Button {
    // ...
    onPressed: {
        state = "pressed"
    }
    // ...
}

這樣,只要按下按鈕(就像以前一樣),state 就會改變,您不需要使用buttonPreessed屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM