qml TableView 的model是c++ QAbstractTableModel 继承的MyTableModel, 写一个例子并实现点击表头实现列排序功能

动态 未结 0 71
小小草
小小草 LV1 2023年9月23日 23:40 发表
好的,下面是一个示例代码,演示如何在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
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复