1
votes

I have subclasses the QAbstractTableModel and provided the headerData override:

/**
 * @brief   Obtains the header (columns) names.
 * @param   section: column number.
 * @param   orientation: Accepts only horizontal.
 * @param   role: Accepts only display.
 * @return  The column header text in case all params are valid.
 *          Otherwise empty QVariant.
 */
QVariant CVarTableModel::headerData(int section,
                                    Qt::Orientation orientation,
                                    int role) const
{
    if (role != Qt::DisplayRole)
        return QVariant();

    if (orientation != Qt::Horizontal)
        return QVariant();

    if (section >= static_cast<int>(Columns::ZCOUNT))
        return QVariant();

    return QVariant::fromValue(static_cast<Columns>(section));
}

I am trying to figure out how to make my QML TableView component utilize this function. Is there a way to do this automatically?

1

1 Answers

1
votes

Make your method invokbale from QML by using the macro Q_INVOKABLE. Then, use it in your QML as any other method:

class Model: public QStandardItemModel
{
public:
    Model(QObject* parent=nullptr): QStandardItemModel(parent)
    {
        setColumnCount(2);
        setRowCount(2);
    }

    Q_INVOKABLE virtual QVariant headerData(int section,
                                        Qt::Orientation orientation,
                                        int role=Qt::DisplayRole) const override
    {
        qDebug() << section << orientation << role;
        if (role != Qt::DisplayRole)
            return QVariant();

        if (section == 0)
            return "First Column";
        return "Not first column";
    }
};
// In main.cpp
Model* model = new Model();

QQuickView *view = new QQuickView;

view->rootContext()->setContextProperty("myModel", model);

view->setSource(QUrl("qrc:/main.qml"));
view->show();
TableView {
    TableViewColumn {
        role: "title"
        title: myModel.headerData(0, Qt.Vertical);
        width: 100
    }
    TableViewColumn {
        role: "author"
        title: myModel.headerData(1, Qt.Vertical);
        width: 200
    }
    model: myModel
}