繁体   English   中英

使用QML ListView和C ++ QList时如何使用过渡动画 <QObject*> ?

[英]How to have transition animations when using QML ListView and C++ QList<QObject*>?

我正在使用QtQuick 2.0和QML ListView,我用C ++(对象的QList)连接到我的模型。 连接是通过QQmlContext :: setContextProperty()进行的。

现在文档告诉我,界面没有直接的方法来了解变化,所以每当我改变模型时我都只实现了上下文。 但是,当我这样做时,视图直接实现而不触发任何事件(例如添加或删除事件),这让我有点恼火,因为我无法控制转换。

简单地说就是我的qml代码:

ListView {
id : list
        boundsBehavior: Flickable.StopAtBounds

        anchors {
            top: titleBar.bottom
            topMargin: -1
            bottom: mainWindow.bottom
            bottomMargin: -1
        }
        width: mainWindow.width

        model: episodes
        delegate: Episode {
            id: myDelegate
            onShowClicked: episodes.append(episodes[index])
        }

        ScrollBar {
            flickable: list;
        }
    }

Episode是我的自定义委托。 它包含以下代码:

ListView.onAdd: SequentialAnimation {
    PropertyAction { target: episodeDelegate; property: "height"; value: 0 }
    NumberAnimation { target: episodeDelegate; property: "height"; to: 80; duration: 250; easing.type: Easing.InOutQuad }
}

ListView.onRemove: SequentialAnimation {
    PropertyAction { target: episodeDelegate; property: "ListView.delayRemove"; value: true }
    NumberAnimation { target: episodeDelegate; property: "height"; to: 0; duration: 250; easing.type: Easing.InOutQuad }

    // Make sure delayRemove is set back to false so that the item can be destroyed
    PropertyAction { target: episodeDelegate; property: "ListView.delayRemove"; value: false }
}

这是Qt例子的直接副本。

总而言之,模型已正确链接和同步,但这样做的方式使我无法了解QML逻辑中模型更改的本质。

有谁知道任何伎俩?

重置setContextProperty ,可以使用populate转换。 但是,这会同时应用到列表中所有元素的转换。

如果您想在每次添加项目时都有动画,可以使用信号来完成。 例如:

class SomeList : public QObject
{
    Q_OBJECT
public:
    explicit SomeList(QObject *parent = 0);

    void Add(QString color, QString value)
    {
        emit addNew(color,value);
    }

signals:
    void addNew(QString data1,QString data2);
};

在main.cpp中你可以:

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    engine.rootContext()->setContextProperty("cppInstance",new SomeList);

    return app.exec();
}

在QML中:

ListModel{
    id:someListModel
}

Rectangle{
    width: 600
    height: 600
    ListView{
        model:someListModel
        delegate:Rectangle{
            width: parent.width
            height: parent.height/10
            color: model.color
            Text{
                text: value
            } 
        }
    }
    Connections{
        target: cppInstance
        onAddNew: { someListModel.insert(0,{"color":data1,"value":data2})}
    } 
}

SomeList类中,您还可以将QList作为成员,其中包含您在QML中插入的字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM