1
votes

I created QAbstractTableModel subclass for represent it's like a table in Qml. When in qml i used GridView, or ListView items, they used only first column to represent. According to documentation : http://doc.qt.io/qt-5/qml-qtquick-gridview.html this classes uses QAbstractListModel. Is there any class, to correct representation QAbstractTableModel in qml, like a Grid?

There is .h file of my Model (All functions below are implemented in C++)

class ButtonModel : public QAbstractTableModel
{
    Q_OBJECT
public:
    enum ButtonRoles {
        BUTTON_ID_ROLE = Qt::UserRole + 1,
    };
    enum ColumnNames{
        FIRST = 0,
        SECOND,
        THIRD,
        FOURTH,
        FIFTH,
        SIXTH,
        SEVENTH,
        LAST
    };

    ButtonModel(QObject* parent = 0);

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
    bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
    bool loadModel (const QVector<QHash<ColumnNames, Button *>> &buttons, const QModelIndex &parent = QModelIndex());
private:
    QVector<QHash<ColumnNames, Button*>> _buttons;
};

And data() function implementation

QVariant ButtonModel::data(const QModelIndex &index, int role) const
{
    if ((!index.isValid()) || (this->rowCount() <= index.row()) || (this->columnCount() <= index.column())){
        return QVariant();
    }
    switch (role){
        case ButtonRoles::BUTTON_ID_ROLE:
            return QVariant(_buttons[index.row()][ColumnNames(index.column())]->buttonId());
            break;
        case Qt::DisplayRole:
            return QVariant(_buttons[index.row()][ColumnNames(index.column())]->displayText());
            break;
        default:
            return QVariant();
    }
}
1
How many columns / rows are you expecting? This might influence the design. I think your best choice is to use a ListView where delegate contains multiple columns, reading data from different roles of a QAbstractListModel, or from different properties of a QList<QObject*> model - Mark Ch
There are 4x8 table. Yes, i will use QAbstractListModel +GridView/GridLayout pair. - Nikxp
To be clear, I am not recommending gridview or gridlayout. I do not think either are a suitable approach for creating a table. I am suggesting a ListView with a RowLayout in the delegate. - Mark Ch

1 Answers

0
votes

You probably want a QTableView not a QGridView.

A grid view is really just a different layout for a list, whereas a table view does have multiple columns and can take its model data from a C++ QAbstractTableModel.

TableView QML Type | Qt Quick Controls 5.9