Qter 发表于 2017-2-10 18:20:20

Qt之QHeaderView排序

本帖最后由 Qter 于 2017-2-10 18:33 编辑


Qt之QHeaderView排序QTableView *pTableView = new QTableView(this);
TableModel *pModel = new TableModel(this);
QSortFilterProxyModel *pProxyModel = new QSortFilterProxyModel(this);
// 设置数据源模型
pProxyModel->setSourceModel(pModel);
pTableView->setModel(pProxyModel);
// 设置可排序
pTableView->setSortingEnabled(true);
// 设置按照文件名升序排列
pTableView->sortByColumn(FILE_NAME_COLUMN, Qt::AscendingOrder);

// 构造数据,更新界面
QList<FileRecord> recordList;

// 获取随机值
QTime time = QTime::currentTime();
qsrand(time.msec() + time.second()*1000);

for (int i = 0; i < 5; ++i)
{
    int nIndex = qrand()%20 + 1;
    int nHour = qrand()%24;
    int nMinute = qrand()%60;
    int nSecond = qrand()%60;
    int nBytes = qrand()%100000;

    QDateTime dateTime(QDate(2016, 5, 1), QTime(nHour, nMinute, nSecond));

    FileRecord record;
    record.strFileName = QString("Name %1.cpp").arg(nIndex);
    record.dateTime = dateTime;
    record.nSize = nBytes;

    recordList.append(record);
}
pModel->updateData(recordList); Qt之QHeaderView自定义排序(QSortFilterProxyModel)SortFilterProxyModel::SortFilterProxyModel(QWidget *parent)
    : QSortFilterProxyModel(parent)
{

}

SortFilterProxyModel::~SortFilterProxyModel()
{

}

bool SortFilterProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
{
    if (!source_left.isValid() || !source_right.isValid())
      return false;

    if ((source_left.column() == FILE_NAME_COLUMN) && (source_right.column() == FILE_NAME_COLUMN))
    {
      QVariant leftData = sourceModel()->data(source_left);
      QVariant rightData = sourceModel()->data(source_right);

      if (leftData.canConvert<QString>() && rightData.canConvert<QString>())
      {
            QString strLeft = leftData.toString();
            QString strRight = rightData.toString();

            // 去掉后缀.cpp
            if (strLeft.contains("."))
            {
                int nIndex = strLeft.lastIndexOf(".");
                strLeft = strLeft.left(nIndex);
            }
            if (strRight.contains("."))
            {
                int nIndex = strRight.lastIndexOf(".");
                strRight = strRight.left(nIndex);
            }

            // 比较大小,如果字符串相同,则比较后面的整形数据
            QStringList strLeftList = strLeft.split(" ");
            QStringList strRightList = strRight.split(" ");
            if ((strLeftList.count() >= 2) && (strRightList.count() >= 2))
            {
                int nResult = QString::compare(strLeftList.at(0), strRightList.at(0), Qt::CaseInsensitive);
                if (nResult == 0)
                {
                  return strLeftList.at(1).toInt() < strRightList.at(1).toInt();
                }
                else
                {
                  return nResult;
                }
            }
      }
    }

    return QSortFilterProxyModel::lessThan(source_left, source_right);
} Qt之QHeaderView自定义排序(终极版)


页: [1]
查看完整版本: Qt之QHeaderView排序