好的,下面是一个示例代码,演示如何在QML TableView中使用自定义的C++ QAbstractTableModel,并实现点击表头实现列排序功能:
MyTableModel.h
```cpp
#ifndef MYTABLEMODEL_H
#define MYTABLEMODEL_H
#include
class MyTableModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit MyTableModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
Qt::ItemFlags flags(const QModelIndex &index) const override;
private:
QList> m_data;
};
#endif // MYTABLEMODEL_H
```
MyTableModel.cpp
```cpp
#include "MyTableModel.h"
MyTableModel::MyTableModel(QObject *parent)
: QAbstractTableModel(parent)
{
// 初始化数据
m_data = {
{"Alice", 25},
{"Bob", 30},
{"Charlie", 20},
{"David", 35}
};
}
int MyTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return m_data.size();
}
int MyTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 2;
}
QVariant MyTableModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (role == Qt::DisplayRole || role == Qt::EditRole) {
int row = index.row();
int col = index.column();
if (row < 0 || row >= m_data.size())
return QVariant();
if (col < 0 || col >= 2)
return QVariant();
return m_data[row][col];
}
return QVariant();
}
QVariant MyTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal) {
switch (section