74 lines
1.9 KiB
C++
74 lines
1.9 KiB
C++
#include "fruitmodel.h"
|
|
#include <QStringList>
|
|
|
|
FruitModel::FruitModel(QObject *parent)
|
|
: QAbstractTableModel(parent) {
|
|
}
|
|
|
|
|
|
|
|
void FruitModel::addFruit(const Fruit &fruit) {
|
|
beginInsertRows(QModelIndex(), fruits.count(), fruits.count());
|
|
fruits.append(fruit);
|
|
endInsertRows();
|
|
}
|
|
|
|
Qt::ItemFlags FruitModel::flags(const QModelIndex& index) const {
|
|
if (!index.isValid())
|
|
return Qt::NoItemFlags;
|
|
|
|
// 返回默认的标志,并添加 Qt::ItemIsEditable
|
|
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
|
|
}
|
|
|
|
int FruitModel::rowCount(const QModelIndex &parent) const {
|
|
Q_UNUSED(parent);
|
|
return fruits.count();
|
|
}
|
|
|
|
int FruitModel::columnCount(const QModelIndex &parent) const {
|
|
Q_UNUSED(parent);
|
|
return 3; // 水果型号, 产地, 品质数量
|
|
}
|
|
|
|
QVariant FruitModel::data(const QModelIndex &index, int role) const {
|
|
if (!index.isValid()) {
|
|
return QVariant();
|
|
}
|
|
|
|
const Fruit &fruit = fruits.at(index.row());
|
|
|
|
if (role == Qt::DisplayRole) {
|
|
switch (index.column()) {
|
|
case 0: // 水果型号
|
|
return fruit.name;
|
|
case 1: // 产地
|
|
return fruit.origin;
|
|
case 2: // 品质数量
|
|
return QString("大: %1 \n中: %2 \n小: %3")
|
|
.arg(fruit.largeQuantity)
|
|
.arg(fruit.mediumQuantity)
|
|
.arg(fruit.smallQuantity);
|
|
}
|
|
} else if (role == Qt::DecorationRole && index.column() == 1) {
|
|
return fruit.icon;
|
|
}
|
|
|
|
return QVariant();
|
|
}
|
|
|
|
QVariant FruitModel::headerData(int section, Qt::Orientation orientation, int role) const {
|
|
if (role == Qt::DisplayRole) {
|
|
if (orientation == Qt::Horizontal) {
|
|
switch (section) {
|
|
case 0:
|
|
return "水果型号";
|
|
case 1:
|
|
return "产地";
|
|
case 2:
|
|
return "品质数量";
|
|
}
|
|
}
|
|
}
|
|
return QVariant();
|
|
} |