13.3.1.  Standard or Abstract?

[ fromfile: tablemodels.xml id: standardorabstract ]

When programmers first get acquainted with QStandardItem, they sometimes use it in situations where it might not be the best choice. Although QStandardItemModel can make it a bit easier to build a model without the need for inheritance from an abstract base class, if you are concerned about QStandardItem data's failing to stay in sync with other data in memory, or that it takes too long to create the standard items initially, these could be indicators that you should derive directly or indirectly from a QAbstractItemModel instead.

Example 13.10 is an example of a QStandardItem-based class for a shortcut table model.

Example 13.10. src/modelview/shortcutmodel-standarditem/actiontableeditor.h

[ . . . . ]
class ActionTableEditor : public QDialog {
    Q_OBJECT
public:
    ActionTableEditor(QWidget* parent = 0);
    ~ActionTableEditor();
protected slots:
    void on_m_tableView_activated(const QModelIndex& idx=QModelIndex());
    QList<QStandardItem*> createActionRow(QAction* a);
protected:
    void populateTable();
    void changeEvent(QEvent* e);
private:
    QList<QAction*> m_actions;
    QStandardItemModel* m_model;
    Ui_ActionTableEditor* m_ui;
};
[ . . . . ]

<include src="src/modelview/shortcutmodel-standarditem/actiontableeditor.h" href="src/modelview/shortcutmodel-standarditem/actiontableeditor.h" id="shortcut-stditem-classdef" allfiles="1" mode="cpp"/>


Because this is a Designer form, the widgets were created and instantiated in generated code that looks like Example 13.11.

Example 13.11. src/modelview/shortcutmodel-standarditem/actiontableeditor_ui.h

[ . . . . ]
class Ui_ActionTableEditor
{
public:
  QVBoxLayout *verticalLayout;
  QTableView *m_tableView;
  QSpacerItem *verticalSpacer;
  QDialogButtonBox *m_buttonBox;

  void setupUi(QDialog *ActionTableEditor)
  {
    if (ActionTableEditor->objectName().isEmpty())
      ActionTableEditor->setObjectName(QString::
                                       fromUtf8("ActionTableEditor"));
    ActionTableEditor->resize(348, 302);
    verticalLayout = new QVBoxLayout(ActionTableEditor);
    verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
    m_tableView = new QTableView(ActionTableEditor);
    m_tableView->setObjectName(QString::fromUtf8("m_tableView"));
    verticalLayout->addWidget(m_tableView);
[ . . . . ]

<include src="src/modelview/shortcutmodel-standarditem/actiontableeditor_ui.h" href="src/modelview/shortcutmodel-standarditem/actiontableeditor_ui.h" id="ui-actiontableeditor-h" allfiles="1" mode="cpp"/>


Example 13.12 shows how to create rows of data, one per QAction, in a QStandardItemModel.

Example 13.12. src/modelview/shortcutmodel-standarditem/actiontableeditor.cpp

[ . . . . ]

QList<QStandardItem*> ActionTableEditor::
createActionRow(QAction* a) {
    QList<QStandardItem*> row;
    QStandardItem* actionItem = new QStandardItem(a->text());
    QStandardItem* shortcutItem = 
        new QStandardItem(a->shortcut().toString());                1
    actionItem->setIcon(a->icon());                                 2
          
    actionItem->setToolTip(a->toolTip());                           3
    actionItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); 4
    shortcutItem->setFlags(Qt::ItemIsSelectable| Qt::ItemIsEnabled);
    shortcutItem->setIcon(a->icon());                               5
    row << actionItem << shortcutItem;
    return row;
}

void ActionTableEditor::populateTable() {
    foreach (QWidget* w, qApp->topLevelWidgets())                   6
        foreach (QAction* a, w->findChildren<QAction*>()) {         7            
            if (a->children().size() > 0) continue;                 8
            if (a->text().size() > 0) m_actions << a;
        }

    int rows = m_actions.size();
    m_model = new QStandardItemModel(this);
    m_model->setColumnCount(2);
    m_model->setHeaderData(0, Qt::Horizontal, QString("Action"),
                           Qt::DisplayRole);
    m_model->setHeaderData(1, Qt::Horizontal, QString("Shortcut"),
                           Qt::DisplayRole);
    QHeaderView* hv = m_ui->m_tableView->horizontalHeader();
    m_ui->m_tableView->
       setSelectionBehavior(QAbstractItemView::SelectRows);
    m_ui->m_tableView->
       setSelectionMode(QAbstractItemView::NoSelection);
    hv->setResizeMode(QHeaderView::ResizeToContents);
    hv->setStretchLastSection(true);
    m_ui->m_tableView->verticalHeader()->hide();
    for (int row=0; row < rows; ++row ) {
        m_model->appendRow(createActionRow(m_actions[row]));
    }
    m_ui->m_tableView->setModel(m_model);                           9
}

1

Duplicating data from QAction to QStandardItem.

2

More duplicate data.

3

More duplicate data.

4

Read-only model without Qt::ItemIsEditable.

5

More duplicate data.

6

All top level widgets.

7

All QActions that can be found.

8

Skip groups of actions.

9

Connect the view to its model.

<include src="src/modelview/shortcutmodel-standarditem/actiontableeditor.cpp" mode="cpp" href="src/modelview/shortcutmodel-standarditem/actiontableeditor.cpp" id="shortcut-stditem-populate" segid="populate"/>


QStandardItem has its own properties, so we copy values from each QAction into two corresponding Items. This kind of duplication of data can have huge performance and memory impact when working with large data models. The main point of this is, there is a significant overhead just creating the model, and we throw it away when we are done with it.

This example does not use the editing features of the View to change data in the Model. That requires writing a delegate to provide a custom editor widget and is left as an exercise for the reader (Exercise 4 in Section 13.6). Instead, a Dialog is popped up when the user activates a row, as shown in Example 13.13. When the Dialog is Accepted, the QAction's shortcut is set directly, bypassing the model entirely. The next time you display this shortcut table, the model must be regenerated from the action list again, or else we need to handle changes properly.

Example 13.13. src/modelview/shortcutmodel-standarditem/actiontableeditor.cpp

[ . . . . ]

void ActionTableEditor::
on_m_tableView_activated(const QModelIndex& idx) {
    int row = idx.row();
    QAction* action = m_actions.at(row);
    ActionEditorDialog aed(action);
    int result = aed.exec();                        1
    if (result ==  QDialog::Accepted) {             2
        action->setShortcut(aed.keySequence());     3
        m_ui->m_tableView->reset();
    }
}

1

Pop up modal dialog for editing an action's shortcut.

2

This would be a good place to check for duplicate/ambiguous bindings.

3

Skip the model and set the QAction property directly.

<include src="src/modelview/shortcutmodel-standarditem/actiontableeditor.cpp" mode="cpp" href="src/modelview/shortcutmodel-standarditem/actiontableeditor.cpp" id="actiontableeditor-activated" segid="dialog"/>


A better approach...

Example 13.14 is an example of a table model that extends QAbstractTableModel by implementing data() and flags(), the pure virtual methods that provide access to model data. The model is a proxy for a list of QActions that are already in memory. This means there is no duplication of data in the model.

Example 13.14. src/libs/actioneditor/actiontablemodel.h

[ . . . . ]
class ACTIONEDITOR_EXPORT ActionTableModel : public QAbstractTableModel {
    Q_OBJECT
 public:
    explicit ActionTableModel(QList<QAction*> actions, QObject* parent=0);
    int rowCount(const QModelIndex&  = QModelIndex()) const {
        return m_actions.size();
    }
    int columnCount(const QModelIndex& = QModelIndex()) const {
        return m_columns;
    }
    QAction* action(int row) const;
    
    QVariant headerData(int section, Qt::Orientation orientation,   1
        int role) const;  
    QVariant data(const QModelIndex& index, int role) const;        2
    Qt::ItemFlags flags(const QModelIndex& index) const;            3
    bool setData(const QModelIndex& index, const QVariant& value, 
        int role = Qt::EditRole);                                   4
    
 protected:
    QList<QAction*> m_actions;
    int m_columns;
};
[ . . . . ]

1

Optional override.

2

Required override.

3

required override.

4

Required for an editable model.

<include src="src/libs/actioneditor/actiontablemodel.h" href="src/libs/actioneditor/actiontablemodel.h" id="actiontablemodel.h" mode="cpp"/>


Example 13.15 shows the implementation of data() Notice that for many of the different properties of a QAction, there is an equivalent data role. You can think of a role (especially a user role) as an additional column of data.

Example 13.15. src/libs/actioneditor/actiontablemodel.cpp

[ . . . . ]

QVariant ActionTableModel::
data(const QModelIndex& index, int role) const {
    int row = index.row();
    if (row >= m_actions.size()) return QVariant();
    int col = index.column();
    if (col >= columnCount()) return QVariant();
    if (role == Qt::DecorationRole)  
        if (col == 0)
            return m_actions[row]->icon();
    
    if (role == Qt::ToolTipRole) {
        return m_actions[row]->toolTip();
    }
    if (role == Qt::StatusTipRole) {
        return m_actions[row]->statusTip();
    }
    if (role == Qt::DisplayRole) {
        if (col == 1) return m_actions[row]->shortcut();
        if (col == 2) return m_actions[row]->parent()->objectName();
        else return m_actions[row]->text();
    }
    return QVariant();
}

<include segid="data" mode="cpp" href="src/libs/actioneditor/actiontablemodel.cpp" id="actiontablemodel.cpp" src="src/libs/actioneditor/actiontablemodel.cpp"/>


The ActionTableModel above is lightweight, in the sense that it creates/copies no data. It presents the data to the view only when the view asks for it. This means it is possible to implement sparse data structures behind a data model. This also means models can fetch data in a lazy fashion from another source, as is the case with QSqlTableModel and QFileSystemModel.