4

当绑定发生变化时,我正在尝试找到一种方法来对 QML 元素进行转换。假设您有一个Text元素,其text属性绑定到某物。我想要的是当绑定中的数据发生变化时,元素淡出(仍然显示旧数据),切换并淡入新数据(实际转换发生在元素不可见时。)

我一直在到处寻找一种方法来做到这一点,但我可以弄清楚。我曾尝试在 QML 中使用 Qt Quick 动画,但数据本身会在动画运行之前发生变化,从而使动画变得不必要。我尝试创建一个自定义 QDeclarativeItem 对象,该对象在其中调用动画,QDeclarativeItem::paint()但我不知道如何让它实际运行。

我应该在这里注意,我知道我的绑定在显示的数据发生变化时工作正常,我只是无法让这些动画在适当的时间运行。

这是我尝试使用 QML 的方法:

Text {
    id: focusText
    text: somedata

    Behavior on text {
         SequentialAnimation {
             NumberAnimation { target: focusText; property: "opacity"; to: 0; duration: 500 }
             NumberAnimation { target: focusText; property: "opacity"; to: 1; duration: 500 }
         }
     }
}

这是我在实现自定义时尝试的QDeclarativeItem

// PAINTER
void AnimatedBinding::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
    // Setup the pen
    QPen pen(m_color, 2);
    painter->setPen(pen);
    painter->setOpacity(this->opacity());

    // Draw the item
    if (m_bindingType == QString("text")) {
        QPropertyAnimation animation(this, "opacity");
        animation.setDuration(1000);
        animation.setStartValue(1);

        if (drawn) {
            animation.setStartValue(1);
            animation.setEndValue(0);
            animation.start();
        } else drawn = true;

        painter->drawText(boundingRect(), m_data.toString());
        animation.setEndValue(0);
        animation.start();
    } else {
        qCritical() << "Error unknown binding type!";
        return;
    }
}

但就像我说的,我在画家内部开始的动画从未真正触发过。

有小费吗?以前有人做过吗?大约一个星期以来,我一直在努力解决这个问题。

4

1 回答 1

2

仅以这种方式在 qml 中执行此操作怎么样:

  1. 定义您自己类型的自定义元素,它的行为方式符合您的要求。
  2. 使用此元素代替传统元素进行动画处理。

例如。我创建了一个自定义的“AnimatedText”类型,以便在与文本元素相关的文本发生更改时对文本元素进行淡入和淡出行为。

文件 1:AnimatedText.qml

import QtQuick 1.0

Item
{
    id: topParent
    property string aText: ""
    property string aTextColor: "black"
    property int aTextFontSize: 10
    property int aTextAnimationTime : 1000

    Behavior on opacity { NumberAnimation { duration: aTextAnimationTime } }

    onATextChanged:
    {
         topParent.opacity = 0
         junkTimer.running = true
    }

    Timer
    {
       id: junkTimer
       running: false
       repeat: false
       interval: aTextAnimationTime
       onTriggered:
       {
           junkText.text = aText
           topParent.opacity = 1
       }
    }

    Text
    {
        id: junkText
        anchors.centerIn: parent
        text: ""
        font.pixelSize: aTextFontSize
        color: aTextColor
    }
}

在你的 main.qml

import QtQuick 1.0

Rectangle
{
    id: topParent
    width:  360
    height: 360

    AnimatedText
    {
      id: someText

      anchors.centerIn: parent
      aText: "Click Me to change!!!.."
      aTextFontSize: 25
      aTextColor: "green"
      aTextAnimationTime: 500
    }

    MouseArea
    {
        anchors.fill: parent
        onClicked:
        {
            someText.aText = "Some random junk"
        }
    }
}
于 2013-01-15T18:57:36.087 回答