当前位置: 代码迷 >> QT开发 >> 关于使用Qt中Model/View中Qt:ItemDataRole的一些疑义
  详细解决方案

关于使用Qt中Model/View中Qt:ItemDataRole的一些疑义

热度:821   发布时间:2016-04-25 02:51:56.0
关于使用Qt中Model/View中Qt::ItemDataRole的一些疑问
诚如《CppGuiProgrammingWithQt4》中第十章的例子,介绍使用模型/视图的方法处理具体数据,每个对应的索引都可以根据不同的role同时保存不同的数据。如Qt::EditRole、Qt::DisplayRole、Qt::Qt::ToolTipRole等不同role。但是在cities例子中setData和data方法对于同样的数据为什么要用不同的role来进行判断?特别是Qt::EditRole、Qt::DisplayRole这两个role有什么具体不同?
具体例子:
QVariant CityModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    if (role == Qt::TextAlignmentRole) {
        return int(Qt::AlignRight | Qt::AlignVCenter);
    } else if (role == Qt::DisplayRole) { //显示role时,读取具体的距离数据
    //} else if (Qt::EditRole == role) {
        if (index.row() == index.column())
            return 0;
        int offset = offsetOf(index.row(), index.column());
        return distances[offset];
    }
    return QVariant();
}


bool CityModel::setData(const QModelIndex &index,
                        const QVariant &value, int role)
{
    if (index.isValid() && index.row() != index.column()
            && role == Qt::EditRole) { //编辑role时,将获取的距离数据保存
        int offset = offsetOf(index.row(), index.column());
        distances[offset] = value.toInt();

        QModelIndex transposedIndex = createIndex(index.column(),
                                                  index.row());
        emit dataChanged(index, index);
        emit dataChanged(transposedIndex, transposedIndex);
        return true;
    }

    return false;
}

------解决思路----------------------
Qt::EditRole、Qt::DisplayRole大部分model都是等同的,会有类似语句:
 role = (role == Qt::EditRole) ? Qt::DisplayRole : role;
顾名思义, Qt::DisplayRole是显示值,Qt::EditRole才是真实值,如true与false, 如果显示为真、假或是、否就直观些,再如一些枚举值,如果显示为数字无法理解,用Qt::DisplayRole显示为中文就明了。
  相关解决方案