2014-02-26 63 views
4

我正在使用QtQuick 2.0和QML ListView,我使用C++(对象的QList)连接到我的模型。连接是通过QQmlContext :: setContextProperty()完成的。如何在使用QML ListView和C++时使用过渡动画QList <QObject*>?

现在文档告诉我没有直接的方法让界面知道有关更改,所以我只在每次更改模型时都实现了上下文。然而,当我这样做时,视图直接执行而不会触发任何事件(例如添加或移除事件),这让我感到有些懊恼,因为我无法控制过渡。

简单地说这是我的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; 
     } 
    } 

其中情节是我的自定义委托。它包含以下代码:

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逻辑中模型更改的本质。

有谁知道任何诡计?

回答

3

当您重置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中插入的字符串。

+0

我现在真的没有这个问题了,但我相信你的解决方案在那时确实回答了我的问题。我尽可能多地坚持只用于显示的QML,这就是为什么我没有C++中的List Item,而只是QML中的视图。感谢您花时间。 – Gostron

+0

这是一个不错的解决方案。 – BaCaRoZzo

+0

直到现在还没有看到你问这个问题的日期......我偶然发现了你的问题,因为一个星期前我遇到了同样的问题。希望这个答案能够帮助像我一样处于相同情况的人。 –