QAbstractTableModel :: header数据和QML TableView

时间:2019-06-04 13:30:50

标签: c++ qt qml

我有QAbstractTableModel的子类,并提供了headerData覆盖:

/**
 * @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));
}

我试图弄清楚如何使我的QML TableView组件利用此功能。有没有办法自动执行此操作?

1 个答案:

答案 0 :(得分:1)

通过使用宏Q_INVOKABLE从QML进行方法调用。然后,将其作为其他方法在您的QML中使用:

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
}