In case someone wants to reproduce this:
headers are displayed correctly if if use tableModel in the qml file, and it stops working if I use sortModel
main.qml
import QtQuick 2.15
import QtQuick.Window 2.15
import Qt.labs.qmlmodels 1.0
import QtQuick.Controls 2.15
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
HorizontalHeaderView {
id: horizontalHeader
syncView: tableView
anchors.left: tableView.left
}
VerticalHeaderView {
id: verticalHeaderView
syncView: tableView
anchors.right: tableView.left
anchors.top: tableView.top
}
TableView {
id: tableView
anchors.fill: parent
anchors.margins: 50
model: sortModel
delegate: Rectangle {
width: 30
height: 30
border.color: "black"
Text{
color: "black"
text: model.display
}
}
}
}
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QSortFilterProxyModel>
#include "tablemodel.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
TableModel tm;
engine.rootContext()->setContextProperty("tableModel",&tm);
QSortFilterProxyModel sortModel;
sortModel.setSourceModel(&tm);
engine.rootContext()->setContextProperty("sortModel",&sortModel);
engine.load(url);
return app.exec();
}
tablemodel.h
#ifndef TABLEMODEL_H
#define TABLEMODEL_H
#include <QAbstractTableModel>
class TableModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit TableModel(QObject *parent = nullptr);
// Header:
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
// Basic functionality:
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;
private:
};
#endif // TABLEMODEL_H
tablemodel.cpp
#include "tablemodel.h"
TableModel::TableModel(QObject *parent)
: QAbstractTableModel(parent)
{
}
QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
return section;
}
int TableModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return 5;
}
int TableModel::columnCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return 7;
}
QVariant TableModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
return QVariant::fromValue(QString::number(index.row())+","+QString::number(index.column()));
}