2015-10-28 38 views
2

我必須製作一個由C++控制的機械計數器。我是從包含數字(0,1,2,3,4,5,6,7,8,9,0)的圖像中完成的。一次只能看到一個數字。我希望這個櫃檯只能向一個方向改變(上),並且我提出了這個理論:如果新數字比舊數字小,我首先進入最後一個零,然後禁用動畫,然後轉到第一個零,啓用動畫並最終轉到想要的數字。但是這不會工作。 它會立即移動到第一個零,然後將動畫轉到想要的數字。下面是代碼:QML如何動畫屬性的每個變化? (只有最後一個更改動畫可見)

import QtQuick 2.4 
import QtQuick.Window 2.2 
Window { 
    id: mainWindow 
    visible: true 
    visibility: "Maximized" 
    property int digit0Y: 0 
    property bool anim0Enabled: true 
    Item { 
     id: root 
     visible: true 
     anchors.fill: parent 
     Rectangle { 
      id: container 
      width: 940; height:172 
      anchors.centerIn: parent 
      clip: true 
      color: "black" 
      NumberElement { 
       id: digit0 
       y: mainWindow.digit0Y; x: 0 
       animationEnabled: anim0Enabled 
      } 
     } 
    } 
} 

的NumberElement.qml:

import QtQuick 2.0 
Rectangle { 
    id: root 
    property bool animationEnabled: true 
    width: 130; height: 1892 
    color: "transparent" 
    Behavior on y { 
     enabled: root.animationEnabled 
     SmoothedAnimation { velocity: 200; duration: 1500; alwaysRunToEnd: true } 
    } 
    Image { 
     id: digits 
     source: "http://s30.postimg.org/6mmsfxdb5/cifre_global.png" 
    } 
} 

編輯:

#include <QQmlComponent> 
#include <QGuiApplication> 
#include <QThread> 
#include <QQmlApplicationEngine> 
#include <QQmlProperty> 
#include <QDebug> 

int number = 0; 
int oldDigit = 0; 

void set(QObject *object, int number) { 
    int newDigit = number%10; 
    if (newDigit < oldDigit) { 
     QQmlProperty::write(object, "digit0Y", -1720); 
     QQmlProperty::write(object, "anim0Enabled", false); 
     QQmlProperty::write(object, "digit0Y", 0); 
     QQmlProperty::write(object, "anim0Enabled", true); 
    } 
    QQmlProperty::write(object, "digit0Y",newDigit*(-172)); 
    oldDigit = newDigit; 
} 
int main(int argc, char *argv[]) 
{ 
    QGuiApplication app(argc, argv); 
    QQmlEngine engine; 
    QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/main.qml"))); 
    if (component.status() == QQmlComponent::Error) { 
     qWarning() << component.errorString(); 
     return 1; 
    } 
    QObject *object = component.create(); 
    set(object, 9); 
    //QThread::msleep(1000); 
    set(object, 1); 
    return app.exec(); 
} 

通常一個單獨的類採取設置數字的照顧,相關的一些事件,但我試圖簡化來證明我的問題。在上面的例子中,數字變爲1,並且不在乎set(object, 9)。這是我的問題。

回答

0

在開始第二個動畫之前,您需要等待第一個動畫完成。你可能會想,「不過我現在alwaysRunToEndtrue ......」,但這並不能幫助這裏:

這個屬性保存,當它停止動畫是否運行完畢。

如果當它停止這個真實的動畫將完成其當前迭​​代 - 通過設置運行屬性設置爲false,或通過調用stop()方法。

什麼是目前發生的事情是,你設置9爲數字,告訴它應該開始動畫的動畫,但後來你給下一個指令是設置1的數字,它告訴動畫停止什麼它正在爲這個新變化做着動畫。

一般來說,處理Qt Quick的動畫是從QML容易。

我也建議PathView這個特定用例,因爲它可能會更容易達到你以後。