Home > Articles > Programming > C/C++

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 {
    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;
};
[ . . . . ]

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);
[ . . . . ]

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.

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

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.

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;
            break;
        }
    }
    if (previousAction != 0) {
        QString error = tr("%1 is already bound to %2.").
                arg(ks.toString()).arg(previousAction->text());
        bool answer = QMessageBox::question(0, error,
                    tr("%1\n Remove previous binding?").arg(error),
                    QMessageBox::Yes, QMessageBox::No);
        if (!answer) return false;
        previousAction->setShortcut(QKeySequence());
    }
    m_actions[row]->setShortcut(ks);
    QModelIndex changedIdx = createIndex(row, 1);                1
    emit dataChanged(changedIdx, changedIdx);                    2
    return true;
}

1

Column 1 displays the shortcut.

2

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;
    s.beginGroup("shortcut");
    foreach (QAction* act, m_changedActions) {
        s.setValue(act->text(), act->shortcut() );
    }
    s.endGroup();
    QDialog::accept();
}

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
}

1

SortFilterProxy source model set to ActionTableModel.

2

Table view model set to proxy model instead of ActionTableModel.

3

Filter on all fields.

4

Auto-connected slot.

5

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020