Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

13.3 Table Models

The next example, pictured in Figure 13.9, is a table model with a view for displaying and editing actions and their corresponding shortcuts. To demonstrate the use and display of the different data roles supported in the Qt Model-View classes, we take a list of QActions and display it in a table. Each action can have an icon, tooltips, status tip, and other user data. These directly correspond to four of the available data roles.

Figure 13.9

Figure 13.9 Shortcut Editor

13.3.1 Standard or Abstract?

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 {
    ActionTableEditor(QWidget* parent = 0);
protected slots:
    void on_m_tableView_activated(const QModelIndex& idx=QModelIndex());
    QList<QStandardItem*> createActionRow(QAction* a);
    void populateTable();
    void changeEvent(QEvent* e);
    QList<QAction*> m_actions;
    QStandardItemModel* m_model;
    Ui_ActionTableEditor* m_ui;
[ . . . . ]

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
  QVBoxLayout *verticalLayout;
  QTableView *m_tableView;
  QSpacerItem *verticalSpacer;
  QDialogButtonBox *m_buttonBox;

  void setupUi(QDialog *ActionTableEditor)
    if (ActionTableEditor->objectName().isEmpty())
    ActionTableEditor->resize(348, 302);
    verticalLayout = new QVBoxLayout(ActionTableEditor);
    m_tableView = new QTableView(ActionTableEditor);

[ . . . . ]

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->setHeaderData(0, Qt::Horizontal, QString("Action"),
    m_model->setHeaderData(1, Qt::Horizontal, QString("Shortcut"),
    QHeaderView* hv = m_ui->m_tableView->horizontalHeader();

    for (int row=0; row < rows; ++row ) {
    m_ui->m_tableView->setModel(m_model);                                9


Duplicating data from QAction to QStandardItem.


More duplicate data.


More duplicate data.


Read-only model without Qt::ItemIsEditable.


More duplicate data.


All top-level widgets.


All QActions that can be found.


Skip groups of actions.


Connect the view to its model.

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 that 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 you (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


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


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


Skip the model and set the QAction property directly.

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 {
    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
    QList<QAction*> m_actions;
    int m_columns;
[ . . . . ]


Optional override.


Required override.


required override.


Required for an editable model.

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();

The ActionTableModel 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.

13.3.2 Editable Models

For editable models, you must override flags() and setData(). If you want in-place editing (in the actual view), you would return Qt::ItemIsEditable from flags(). Because we still pop up an ActionEditorDialog when an item is clicked, we do not need in-place editing so, Example 13.16 simply returns Qt::ItemIsEnabled.

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

[ . . . . ]

Qt::ItemFlags ActionTableModel::
flags(const QModelIndex& index) const {
    if (index.isValid()) return Qt::ItemIsEnabled;
    else return 0;

Example 13.17 shows how, in setData(), you can check for ambiguous shortcuts before actually setting new values. After the data is changed, it is important to emit a dataChanged() signal so that views that may be showing old data know it is time to fetch newer data from the model.

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

[ . . . . ]

bool ActionTableModel::
setData(const QModelIndex& index, const QVariant& value, int role) {

    if (role != Qt::EditRole) return false;
    int row = index.row();
    if ((row < 0) | (row >= m_actions.size())) return false;
    QString str = value.toString();
    QKeySequence ks(str);
    QAction* previousAction = 0;

    if (ks != QKeySequence() ) foreach (QAction* act, m_actions) {
        if (act->shortcut() == ks) {
            previousAction = act;
    if (previousAction != 0) {
        QString error = tr("%1 is already bound to %2.").
        bool answer = QMessageBox::question(0, error,
                    tr("%1\n Remove previous binding?").arg(error),
                    QMessageBox::Yes, QMessageBox::No);
        if (!answer) return false;
    QModelIndex changedIdx = createIndex(row, 1);                1
    emit dataChanged(changedIdx, changedIdx);                    2
    return true;


Column 1 displays the shortcut.


Required for views to know when/what to update.

To support inserting/removing rows, there are analogous signals, rowsInserted() and rowsRemoved(), that you must emit from our implementations of insertRows()/removeRows().

After one or more shortcuts have been changed, you save them to QSettings. Example 13.18 shows how to keep track of the modified QActions that need to be saved.

Example 13.18. src/libs/actioneditor/actiontableeditor.cpp

[ . . . . ]

void ActionTableEditor::
on_m_tableView_activated(const QModelIndex& idx) {

    int row = idx.row();
    QAction* action = m_model->action(row);
    ActionEditorDialog aed(action);

    int result = aed.exec();
    if (result ==  QDialog::Accepted) {
        QKeySequence ks = aed.keySequence();
        m_model->setData(idx, ks.toString());
        m_changedActions << action;

Example 13.19 shows how those shortcuts are saved to QSettings, but only if the user accepts the dialog.

Example 13.19. src/libs/actioneditor/actiontableeditor.cpp

[ . . . . ]

void ActionTableEditor::accept() {
    QSettings s;
    foreach (QAction* act, m_changedActions) {
        s.setValue(act->text(), act->shortcut() );

13.3.3 Sorting and Filtering

Don't bother looking for the code creating the QLineEdit, the clear button, or the connect between the two in Figure 13.10. Those were all defined in Designer and generated by uic.

Thanks to QSortFilterProxyModel, you can add sorting/filtering capability to an existing model with fewer than five lines of code. Figure 13.11 shows how the proxy sits between the view and the model.

Figure 13.10

Figure 13.10 Filtered Table View

Figure 13.11

Figure 13.11 Sort Filter Proxy

Example 13.20 shows what is needed to set up the sort filter proxy in the preceding action table example.

Example 13.20. src/libs/actioneditor/actiontableeditor.cpp

[ . . . . ]

void ActionTableEditor::setupSortFilter() {
    m_sortFilterProxy = new QSortFilterProxyModel(this);
    m_sortFilterProxy->setSourceModel(m_model);                 1
    m_ui->m_tableView->setModel(m_sortFilterProxy);             2
    m_sortFilterProxy->setFilterKeyColumn(-1);                  3

void ActionTableEditor::on_m_filterField_textChanged            4
    (const QString& newText) {
    m_sortFilterProxy->setFilterFixedString(newText);           5


SortFilterProxy source model set to ActionTableModel.


Table view model set to proxy model instead of ActionTableModel.


Filter on all fields.


Auto-connected slot.


Change the filter string.

The filterField_textChanged is an auto-connected slot that gets called whenever the textChanged signal is emitted by the filterField QLineEdit.

  • + Share This
  • 🔖 Save To Your Account