如何在使用QML ListView和C++;QList<;QObject*>;? < >我使用QtQueLD 2和QML ListVIEW,我用C++连接到模型中(对象的QLIST)。连接是通过QQmlContext::setContextProperty()建立的
现在,文档告诉我,接口没有直接的方法来了解更改,所以我只在更改模型时实现上下文。但是,当我这样做时,视图直接实现,而不触发任何事件(例如添加或删除事件),这让我有点恼火,因为我无法控制转换 简单地说,这里是我的qml代码:如何在使用QML ListView和C++;QList<;QObject*>;? < >我使用QtQueLD 2和QML ListVIEW,我用C++连接到模型中(对象的QLIST)。连接是通过QQmlContext::setContextProperty()建立的,c++,qt,listview,qml,C++,Qt,Listview,Qml,现在,文档告诉我,接口没有直接的方法来了解更改,所以我只在更改模型时实现上下文。但是,当我这样做时,视图直接实现,而不触发任何事件(例如添加或删除事件),这让我有点恼火,因为我无法控制转换 简单地说,这里是我的qml代码: ListView { id : list boundsBehavior: Flickable.StopAtBounds anchors { top: titleBar.bottom topMar
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逻辑中模型更改的性质
有人知道什么把戏吗?当您重置
setContextProperty
时,您可以使用填充
转换。但是,这会同时将转换应用于列表中的所有元素
如果希望在每次添加项目时都有一个动画,可以使用信号来实现。例如:
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中插入的字符串。我现在真的不懂这个主题,但我相信您的解决方案确实解决了我当时的问题。我尽我所能坚持QML只为显示,这就是为什么我没有一个列表项在C++中,但只有QML的视图。感谢您抽出时间。这是一个很好的解决方案。直到现在才看到您提问的日期。。。我偶然发现了你的问题,因为一周前我也遇到了同样的问题。希望这个答案能帮助那些和我处境相同的人。