QAbstractTableModel headerData删除标题

时间:2019-04-12 00:24:22

标签: c++ qt

我目前正在尝试根据QTableView进行比赛。因此,我使用QAbstractTableModel来存储数据。我的问题是,当我从QVariant headerData(int section, Qt::Orientation orientation, int role) const override;返回比QVariant()多的其他内容时,标头就会消失,就像在调用hide时那样。我不了解这种行为。

实现,其中标题不可见:

class BossListModel : public QAbstractTableModel {
    Q_OBJECT;

private:
    EvtcData header;

public:
    BossListModel(QObject *parent = nullptr);

    int rowCount(const QModelIndex &parent) const override;
    int columnCount(const QModelIndex &parent) const override;

    QVariant headerData(int section, Qt::Orientation orientation, int role) const override;

    QVariant data(const QModelIndex &index, int role) const override;
};
QVariant BossListModel::headerData(int section, Qt::Orientation orientation, int role) const {
    if(orientation == Qt::Horizontal) {
        switch(section) {
            case 0:
                return QString("Name");
            case 1:
                return QString("Time");
            case 2:
                return QString("Result");
            default:
                return QVariant();
        }
    }

    return QVariant();
}

这是我在MainWindow构造函数中设置listView和ItemModel的方式:

void MainWindow::createTable() {
    bossListModel = new BossListModel(this);

    proxyModel = new QSortFilterProxyModel(this);
    proxyModel->setSourceModel(bossListModel);

    tableView = new QTableView;
    tableView->setModel(proxyModel);
    tableView->verticalHeader()->hide();
    tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tableView->setSortingEnabled(true);

    setCentralWidget(tableView);
}

图片:
enter image description here

实现,其中显示标题,但为空:

QVariant BossListModel::headerData(int section, Qt::Orientation orientation, int role) const {
    return QVariant();
}

图片:
enter image description here

我做错了什么?当我尝试命名标题时,为什么标题不可见?

1 个答案:

答案 0 :(得分:2)

您的Parameters(name=deviceType, value=D22, paramType=CONSTRUCTOR) 覆盖项应测试headerData,并且如果为true,则仅返回所需的内容,否则返回空变量。