我有一个ListView,每个元素都有"name"和"amount"两个角色,我需要统计所有元素的总量并显示出来(例如:"A项":10,"B项":2.总金额为12)我尝试使用"onDataChanged",但它显示错误:无法赋值给不存在的属性"onDataChanged"。如何在qml中处理"数据已更改"通知?
- 主. cpp**
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QStandardItemModel>
#include <QQmlContext>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
QHash<int, QByteArray> roles;
roles[Qt::UserRole + 1] = "name";
roles[Qt::UserRole + 2] = "amount";
QStandardItemModel *model = new QStandardItemModel();
model->setRowCount(0);
model->setItemRoleNames(roles);
engine.rootContext()->setContextProperty("myModel", model);
auto item1 = new QStandardItem();
item1->setData("item1", Qt::UserRole + 1);
item1->setData("10", Qt::UserRole + 2);
model->appendRow(item1);
auto item2 = new QStandardItem();
item2->setData("item2", Qt::UserRole + 1);
item2->setData("1", Qt::UserRole + 2);
model->appendRow(item2);
engine.load(url);
return app.exec();
}
- 主文件. qml**
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Layouts
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
ColumnLayout {
anchors.fill: parent
ListView {
Layout.fillWidth: true
Layout.fillHeight: true
model: myModel
delegate: Text {
text: name + " " + amount
}
onDataChanged: function () {
var number = 0
for(var i = 0; i < myModel.rowCount(); i++) {
var index = myModel.index(i, 0);
number += myModel.data(index, amount)
}
total.text = "Total: " + number
}
}
Rectangle {
Layout.fillWidth: true
height: 20
Text {
id: total
anchors.fill: parent
text: "Total: "
}
}
}
}
1条答案
按热度按时间kuarbcqp1#
您需要监听来自模型的信号,而不是ListView,才能发现数据何时发生了变化。