我正在使用 QtQuick 2.0 和 QML ListView,我用 C++(对象的 QList)连接到我的模型。连接是通过 QQmlContext::setContextProperty() 建立的。
现在文档告诉我,界面没有直接的方法来了解更改,所以我只在更改模型时才实现上下文。但是,当我这样做时, View 会直接实现而不会触发任何事件(例如添加或删除事件),这让我有点恼火,因为我无法控制转换。
这里简单的说就是我的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 是我的自定义委托(delegate)。它包含以下代码:
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 Examples 的直接拷贝。
总而言之,模型已正确链接和同步,尽管这样做的方式使我无法了解我的 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 中插入的字符串。
关于c++ - 使用 QML ListView 和 C++ QList<QObject*> 时如何实现过渡动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22036160/