0

I'm trying to use model/view architecture in C++ and QT and need to understand, how is the best way to divide one cell in QTableView to more rows or more columns and use different widgets for them and also how to display just some columns from the model.

I want to hold this structure per row:

- int
- MyStruct - int
           - QString
- 2ndStruct - double
            - double
- QString

What is important:

  1. Display in 2D table (for example QTableView) - without trees. I can change model, but I need to display it in table.
  2. Display just some of the data from model.
  3. According to row index - select some columns from the parent and also some data from child (structs).

I have couple of questions:

  1. How to implement more rows/columns in one QTableView cell and use different types and different QWidgets for them?
  2. How to select just some data I want to show in view? When I reimplement "columnCount" in model, I can't put constant there because I want use this model in different view. I read tutorials and I found, that there is no need to reimplement view class. How can I select just data I want to show?
  3. Is it better to use 3D model (QStandardItemModel with QStandardItems) or 2D model (QAbstractTableModel) for this case?
Nick
  • 107
  • 3
  • 11

1 Answers1

2

I would suggest to have separate models for different needs, but let them operate on the same data.

I.e. the model classes are just interfaces to the actual data, they don't need to contain the data.

Lets say you have a struct/class called RowData data contains the data you've described.

All rows could then be a list or vector of such objects, e.g. QVector<RowData>

Each model could then operate on the same reference or pointer to such a container

class AllDataInSeparateColumnsModel : public QAbstractTableModel
{
public:
    AllDataInSeparateColumnsModel(QVector<RowData> &data, QObject *parent = nullptr)
        : QAbstractTableModel(parent), m_data(data)
    {}

    int rowCount() const { return m_data.count(); }
    int columnCount() const { return 6; }

private:
    QVector<RowData> &m_data;
};

The data() method for this model could then map column 0 to the first int, column 1 to the int in MyStruct, column 2 to the QString in MyStruct and so on.

If a model needs more than one value per column, then it can define its own additional roles. The view then needs a matching delegate that can retrieve that additional data as required (the standard delegate only displays the string value for Qt::DisplayRole)

Kevin Krammer
  • 5,159
  • 2
  • 9
  • 22