Address Book | Qt Widgets | Qt 6.11.1
Description: The address book example shows how to use proxy models to display different views onto data from a single model.

- Qt 6.11
- Qt Widgets
- Item Views Examples
- Address Book
- Qt 6.11.1 Reference Documentation

# Address Book

The address book example shows how to use proxy models to display different views onto data from a single model.

This example provides an address book that allows contacts to be grouped alphabetically into 9 groups: ABC, DEF, GHI, ... , VW, ..., XYZ. This is achieved by using multiple views on the same model, each of which is filtered using an instance of the QSortFilterProxyModel class.

#### Overview

The address book contains 5 classes: `MainWindow`, `AddressWidget`, `TableModel`, `NewAddressTab` and `AddDialog`. The `MainWindow` class uses `AddressWidget` as its central widget and provides File and Tools menus.

The `AddressWidget` class is a QTabWidget subclass that is used to manipulate the 10 tabs displayed in the example: the 9 alphabet group tabs and an instance of `NewAddressTab`. The `NewAddressTab` class is a subclass of QWidget that is only used whenever the address book is empty, prompting the user to add some contacts. `AddressWidget` also interacts with an instance of `TableModel` to add, edit and remove entries to the address book.

`struct Contact` stores a contact and provides comparison and serialization via QDataStream:

     struct Contact
     {
         QString name;
         QString address;

         friend bool comparesEqual(const Contact &lhs, const Contact &rhs) noexcept
         {
             return lhs.name == rhs.name && lhs.address == rhs.address;
         }

         friend Qt::strong_ordering compareThreeWay(const Contact &lhs, const Contact  &rhs) noexcept
         {
             int cmp = lhs.name.compare(rhs.name);
             if (cmp == 0)
                 cmp = lhs.address.compare(rhs.address);
             return Qt::compareThreeWay(cmp, 0);
         }

         Q_DECLARE_STRONGLY_ORDERED(Contact)
     };

     inline QDataStream &operator<<(QDataStream &stream, const Contact &contact)
     {
         return stream << contact.name << contact.address;
     }

     inline QDataStream &operator>>(QDataStream &stream, Contact &contact)
     {
         return stream >> contact.name >> contact.address;
     }

`TableModel` is a subclass of QAbstractTableModel that provides the standard model/view API to access data. It holds a list of added contacts. However, this data is not all visible in a single tab. Instead, QTableView is used to provide 9 different views of the same data, according to the alphabet groups.

QSortFilterProxyModel is the class responsible for filtering the contacts for each group of contacts. Each proxy model uses a QRegularExpression to filter out contacts that do not belong in the corresponding alphabetical group. The `AddDialog` class is used to obtain information from the user for the address book. This QDialog subclass is instantiated by `NewAddressTab` to add contacts, and by `AddressWidget` to add and edit contacts.

We begin by looking at the `TableModel` implementation.

#### TableModel Class Definition

The `TableModel` class provides standard API to access data in its list of contacts by subclassing QAbstractTableModel. The basic functions that must be implemented in order to do so are: `rowCount()`, `columnCount()`, `data()`, `headerData()`. For TableModel to be editable, it has to provide implementations `insertRows()`, `removeRows()`, `setData()` and `flags()` functions.

     class TableModel : public QAbstractTableModel
     {
         Q_OBJECT

     public:
         explicit TableModel(QObject *parent = nullptr);
         TableModel(const QList<Contact> &contacts, QObject *parent = nullptr);

         int rowCount(const QModelIndex &parent = {}) const override;
         int columnCount(const QModelIndex &parent = {}) const override;
         QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
         QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
         Qt::ItemFlags flags(const QModelIndex &index) const override;
         bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
         bool insertRows(int position, int rows, const QModelIndex &index = {}) override;
         bool removeRows(int position, int rows, const QModelIndex &index = {}) override;

         const QList<Contact> &getContacts() const;

     private:
         QList<Contact> contacts;
     };

Two constructors are used, a default constructor which uses `TableModel`'s own `QList<Contact>` and one that takes `QList<Contact>` as an argument, for convenience.

#### TableModel Class Implementation

We implement the two constructors as defined in the header file. The second constructor initializes the list of contacts in the model, with the parameter value.

     TableModel::TableModel(QObject *parent)
         : QAbstractTableModel(parent)
     {
     }

     TableModel::TableModel(const QList<Contact> &contacts, QObject *parent)
         : QAbstractTableModel(parent), contacts(contacts)
     {
     }

The `rowCount()` and `columnCount()` functions return the dimensions of the model. Whereas, `rowCount()`'s value will vary depending on the number of contacts added to the address book, `columnCount()`'s value is always 2 because we only need space for the Name and Address columns.

     int TableModel::rowCount(const QModelIndex &parent) const
     {
         return parent.isValid() ? 0 : contacts.size();
     }

     int TableModel::columnCount(const QModelIndex &parent) const
     {
         return parent.isValid() ? 0 : 2;
     }

The `data()` function returns either a Name or Address, based on the contents of the model index supplied. The row number stored in the model index is used to reference an item in the list of contacts. Selection is handled by the QItemSelectionModel, which will be explained with `AddressWidget`.

     QVariant TableModel::data(const QModelIndex &index, int role) const
     {
         if (!index.isValid())
             return {};

         if (index.row() >= contacts.size() || index.row() < 0)
             return {};

         if (role == Qt::DisplayRole) {
             const auto &contact = contacts.at(index.row());

             switch (index.column()) {
                 case 0:
                     return contact.name;
                 case 1:
                     return contact.address;
                 default:
                     break;
             }
         }
         return {};
     }

The `headerData()` function displays the table's header, Name and Address. If you require numbered entries for your address book, you can use a vertical header which we have hidden in this example (see the `AddressWidget` implementation).

     QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const
     {
         if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
             switch (section) {
                 case 0:
                     return tr("Name");
                 case 1:
                     return tr("Address");
                 default:
                     break;
             }
         }
         return {};
     }

The `insertRows()` function is called before new data is added, otherwise the data will not be displayed. The `beginInsertRows()` and `endInsertRows()` functions are called to ensure all connected views are aware of the changes.

     bool TableModel::insertRows(int position, int rows, const QModelIndex &index)
     {
         Q_UNUSED(index);
         beginInsertRows(QModelIndex(), position, position + rows - 1);

         for (int row = 0; row < rows; ++row)
             contacts.insert(position, { QString(), QString() });

         endInsertRows();
         return true;
     }

The `removeRows()` function is called to remove data. Again, beginRemoveRows() and endRemoveRows() are called to ensure all connected views are aware of the changes.

     bool TableModel::removeRows(int position, int rows, const QModelIndex &index)
     {
         Q_UNUSED(index);
         beginRemoveRows(QModelIndex(), position, position + rows - 1);

         for (int row = 0; row < rows; ++row)
             contacts.removeAt(position);

         endRemoveRows();
         return true;
     }

The `setData()` function is the function that inserts data into the table, item by item and not row by row. This means that to fill a row in the address book, `setData()` must be called twice, as each row has 2 columns. It is important to emit the dataChanged() signal as it tells all connected views to update their displays.

     bool TableModel::setData(const QModelIndex &index, const QVariant &value, int role)
     {
         if (index.isValid() && role == Qt::EditRole) {
             const int row = index.row();
             auto contact = contacts.value(row);

             switch (index.column()) {
                 case 0:
                     contact.name = value.toString();
                     break;
                 case 1:
                     contact.address = value.toString();
                     break;
                 default:
                     return false;
             }
             contacts.replace(row, contact);
             emit dataChanged(index, index, {Qt::DisplayRole, Qt::EditRole});

             return true;
         }

         return false;
     }

The `flags()` function returns the item flags for the given index.

     Qt::ItemFlags TableModel::flags(const QModelIndex &index) const
     {
         if (!index.isValid())
             return Qt::ItemIsEnabled;

         return QAbstractTableModel::flags(index) | Qt::ItemIsEditable;
     }

We set the Qt::ItemIsEditable flag because we want to allow the `TableModel` to be edited. Although for this example we don't use the editing features of the QTableView object, we enable them here so that we can reuse the model in other programs.

The last function in `TableModel`, `getContacts()` returns the QList<Contact> object that holds all the contacts in the address book. We use this function later to obtain the list of contacts to check for existing entries, write the contacts to a file and read them back. Further explanation is given with `AddressWidget`.

     const QList<Contact> &TableModel::getContacts() const
     {
         return contacts;
     }

#### AddressWidget Class Definition

The `AddressWidget` class is technically the main class involved in this example as it provides functions to add, edit and remove contacts, to save the contacts to a file and to load them from a file.

     class AddressWidget : public QTabWidget
     {
         Q_OBJECT

     public:
         explicit AddressWidget(QWidget *parent = nullptr);

         bool readFromFile();
         bool writeToFile();

         static QString fileName();

     public slots:
         void showAddEntryDialog();
         void addEntry(const Contact &contact);
         void editEntry();
         void removeEntry();

     signals:
         void selectionChanged (const QItemSelection &selected);

     private:
         void setupTabs();

         TableModel *table;
         NewAddressTab *newAddressTab;
     };

`AddressWidget` extends QTabWidget in order to hold 10 tabs (`NewAddressTab` and the 9 alphabet group tabs) and also manipulates `table`, the `TableModel` object, `proxyModel`, the QSortFilterProxyModel object that we use to filter the entries, and `tableView`, the QTableView object.

#### AddressWidget Class Implementation

The `AddressWidget` constructor accepts a parent widget and instantiates `NewAddressTab`, `TableModel` and QSortFilterProxyModel. The `NewAddressTab` object, which is used to indicate that the address book is empty, is added and the rest of the 9 tabs are set up with `setupTabs()`.

     AddressWidget::AddressWidget(QWidget *parent)
         : QTabWidget(parent),
           table(new TableModel(this)),
           newAddressTab(new NewAddressTab(this))
     {
         connect(newAddressTab, &NewAddressTab::triggered, this, &AddressWidget::showAddEntryDialog);

         addTab(newAddressTab, tr("Address Book"));

         setupTabs();
     }

The `setupTabs()` function is used to set up the 9 alphabet group tabs, table views and proxy models in `AddressWidget`. Each proxy model in turn is set to filter contact names according to the relevant alphabet group using a case-insensitive QRegularExpression object. The table views are also sorted in ascending order using the corresponding proxy model's sort() function.

Each table view's selectionMode is set to QAbstractItemView::SingleSelection and selectionBehavior is set to QAbstractItemView::SelectRows, allowing the user to select all the items in one row at the same time. Each QTableView object is automatically given a QItemSelectionModel that keeps track of the selected indexes.

     void AddressWidget::setupTabs()
     {
         const auto groups = { "ABC"_L1, "DEF"_L1, "GHI"_L1, "JKL"_L1, "MNO"_L1, "PQR"_L1,
                               "STU"_L1, "VW"_L1, "XYZ"_L1 };

         for (QLatin1StringView str : groups) {
             const auto regExp = QRegularExpression(QLatin1StringView("^[%1].*").arg(str),
                                                    QRegularExpression::CaseInsensitiveOption);

             auto *proxyModel = new QSortFilterProxyModel(this);
             proxyModel->setSourceModel(table);
             proxyModel->setFilterRegularExpression(regExp);
             proxyModel->setFilterKeyColumn(0);

             auto *tableView = new QTableView;
             tableView->setModel(proxyModel);
             tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
             tableView->horizontalHeader()->setStretchLastSection(true);
             tableView->verticalHeader()->hide();
             tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
             tableView->setSelectionMode(QAbstractItemView::SingleSelection);
             tableView->setSortingEnabled(true);

             connect(tableView->selectionModel(), &QItemSelectionModel::selectionChanged,
                     this, &AddressWidget::selectionChanged);

             connect(this, &QTabWidget::currentChanged, this, [this, tableView](int tabIndex) {
                 if (widget(tabIndex) == tableView)
                     emit selectionChanged(tableView->selectionModel()->selection());
             });

             addTab(tableView, str);
         }
     }

The QItemSelectionModel class provides a selectionChanged signal that is connected to `AddressWidget`'s `selectionChanged()` signal. We also connect QTabWidget::currentChanged() signal to the lambda expression which emits `AddressWidget`'s `selectionChanged()` as well. These connections are necessary to enable the Edit Entry... and Remove Entry actions in `MainWindow`'s Tools menu. It is further explained in `MainWindow`'s implementation.

Each table view in the address book is added as a tab to the QTabWidget with the relevant label, obtained from the QStringList of groups.

We provide two `addEntry()` functions: One which is intended to be used to accept user input, and the other which performs the actual task of adding new entries to the address book. We divide the responsibility of adding entries into two parts to allow `newAddressTab` to insert data without having to popup a dialog.

The first `addEntry()` function is a slot connected to the `MainWindow`'s Add Entry... action. This function creates an `AddDialog` object and then calls the second `addEntry()` function to actually add the contact to `table`.

     void AddressWidget::showAddEntryDialog()
     {
         AddDialog aDialog(this);

         if (aDialog.exec() == QDialog::Accepted)
             addEntry(aDialog.contact());
     }

Basic validation is done in the second `addEntry()` function to prevent duplicate entries in the address book. As mentioned with `TableModel`, this is part of the reason why we require the getter method `getContacts()`.

     void AddressWidget::addEntry(const Contact &contact)
     {
         if (table->getContacts().contains(contact)) {
             QMessageBox::information(this, tr("Duplicate Name"),
                                      tr("The name \"%1\" already exists.").arg(contact.name));
             return;
         }

         table->insertRows(0, 1);
         table->setData(table->index(0, 0), contact.name, Qt::EditRole);
         table->setData(table->index(0, 1), contact.address, Qt::EditRole);
         removeTab(indexOf(newAddressTab));

         const QChar firstChar = contact.name.at(0).toUpper();
         for (int t = 0, tabCount = count(); t < tabCount; ++t) {
             if (tabText(t).contains(firstChar)) {
                 setCurrentIndex(t);
                 break;
             }
         }
     }

If the model does not already contain an entry with the same name, we call `setData()` to insert the name and address into the first and second columns. Otherwise, we display a QMessageBox to inform the user.

Note: The `newAddressTab` is removed once a contact is added as the address book is no longer empty.

Editing an entry is a way to update the contact's address only, as the example does not allow the user to change the name of an existing contact.

Firstly, we obtain the active tab's QTableView object using QTabWidget::currentWidget(). Then we extract the `selectionModel` from the `tableView` to obtain the selected indexes.

     void AddressWidget::editEntry()
     {
         auto *tableView = static_cast<QTableView *>(currentWidget());
         auto *proxy = static_cast<QSortFilterProxyModel *>(tableView->model());
         QItemSelectionModel *selectionModel = tableView->selectionModel();

         const QModelIndexList indexes = selectionModel->selectedRows();
         if (indexes.isEmpty())
             return;

         const int row = proxy->mapToSource(indexes.constFirst()).row();

         Contact contact;
         QModelIndex nameIndex = table->index(row, 0);
         QVariant varName = table->data(nameIndex, Qt::DisplayRole);
         contact.name = varName.toString();
         QModelIndex addressIndex = table->index(row, 1);
         QVariant varAddr = table->data(addressIndex, Qt::DisplayRole);
         contact.address = varAddr.toString();

Next we extract data from the row the user intends to edit. This data is displayed in an instance of `AddDialog` with a different window title. The `table` is only updated if changes have been made to data in `aDialog`.

         AddDialog aDialog(this);
         aDialog.setWindowTitle(tr("Edit a Contact"));
         aDialog.editAddress(contact);

         if (aDialog.exec() == QDialog::Accepted) {
             const Contact newContact = aDialog.contact();
             if (newContact != contact) {
                 const QModelIndex index = table->index(row, 1);
                 table->setData(index, newContact.address, Qt::EditRole);
             }
         }
     }

Entries are removed using the `removeEntry()` function. The selected row is removed by accessing it through the QItemSelectionModel object, `selectionModel`. The `newAddressTab` is re-added to the `AddressWidget` only if the user removes all the contacts in the address book.

     void AddressWidget::removeEntry()
     {
         auto *tableView = static_cast<QTableView *>(currentWidget());
         auto *proxy = static_cast<QSortFilterProxyModel *>(tableView->model());
         QItemSelectionModel *selectionModel = tableView->selectionModel();

         const QModelIndexList indexes = selectionModel->selectedRows();
         if (indexes.isEmpty())
             return;

         const int row = proxy->mapToSource(indexes.constFirst()).row();
         table->removeRows(row, 1);

         if (table->rowCount() == 0)
             insertTab(0, newAddressTab, tr("Address Book"));
     }

The `writeToFile()` function is used to save a file containing all the contacts in the address book. The file is saved in a custom `.dat` format. The contents of the list of contacts are written to `file` using QDataStream. If the file cannot be opened, a QMessageBox is displayed with the related error message.

     bool AddressWidget::writeToFile()
     {
         QFile file(fileName());

         if (!file.open(QIODevice::WriteOnly)) {
             QMessageBox::information(this, tr("Unable to open file"),
                                      tr("Cannot write to %1: %2").arg(QDir::toNativeSeparators(fileName()),
                                                                       file.errorString()));
             return false;
         }

         auto sortedContacts = table->getContacts();
         std::sort(sortedContacts.begin(), sortedContacts.end());

         QDataStream out(&file);
         out << sortedContacts;
         return true;
     }

The `readFromFile()` function loads a file containing all the contacts in the address book, previously saved using `writeToFile()`. QDataStream is used to read the contents of a `.dat` file into a list of contacts and each of these is added using `addEntry()`.

     bool AddressWidget::readFromFile()
     {
         QFile file(fileName());

         if (!file.open(QIODevice::ReadOnly)) {
             QMessageBox::information(this, tr("Unable to open file"),
                                      tr("Cannot open %1: %2").arg(QDir::toNativeSeparators(fileName()),
                                                                   file.errorString()));
             return false;
         }

         QList<Contact> contacts;
         QDataStream in(&file);
         in >> contacts;

         if (contacts.isEmpty()) {
             QMessageBox::information(this, tr("No contacts in file"),
                                      tr("The file you are attempting to open contains no contacts."));
         }

         for (const auto &contact : std::as_const(contacts))
             addEntry(contact);

         return true;
     }

#### NewAddressTab Class Definition

The `NewAddressTab` class provides an informative tab telling the user that the address book is empty. It appears and disappears according to the contents of the address book, as mentioned in `AddressWidget`'s implementation.

The `NewAddressTab` class extends QWidget and contains a QLabel and QPushButton.

     class NewAddressTab : public QWidget
     {
         Q_OBJECT

     public:
         explicit NewAddressTab(QWidget *parent = nullptr);

     signals:
         void triggered();
     };

#### NewAddressTab Class Implementation

The constructor instantiates the `addButton`, `descriptionLabel` and connects the `addButton`'s signal to the `triggered()` signal.

     NewAddressTab::NewAddressTab(QWidget *parent)
         : QWidget(parent)
     {
         auto *descriptionLabel = new QLabel(tr("There are currently no contacts in your address book. "
                                                "\nClick Add to add new contacts."));

         auto *addButton = new QPushButton(tr("Add"));

         connect(addButton, &QAbstractButton::clicked, this, &NewAddressTab::triggered);

         auto *mainLayout = new QVBoxLayout(this);
         mainLayout->addWidget(descriptionLabel, 0, Qt::AlignCenter);
         mainLayout->addWidget(addButton, 0, Qt::AlignCenter);
     }

#### AddDialog Class Definition

The `AddDialog` class extends QDialog and provides the user with a QLineEdit and a QTextEdit to input data into the address book.

     class AddDialog : public QDialog
     {
         Q_OBJECT

     public:
         explicit AddDialog(QWidget *parent = nullptr);

         Contact contact() const;
         void setContact(const Contact &c);

         void editAddress(const Contact &c);

     private slots:
         void updateEnabled();

     private:
         QDialogButtonBox *buttonBox;
         QLineEdit *nameText;
         QPlainTextEdit *addressText;
     };

#### AddDialog Class Implementation

The `AddDialog`'s constructor sets up the user interface, creating the necessary widgets and placing them into layouts.

     AddDialog::AddDialog(QWidget *parent)
         : QDialog(parent),
           buttonBox(new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this)),
           nameText(new QLineEdit),
           addressText(new QPlainTextEdit)
     {
         auto *formLayout = new QFormLayout;
         formLayout->addRow(tr("Name"), nameText);
         formLayout->addRow(tr("Address"), addressText);

         auto *mainLayout = new QVBoxLayout(this);
         mainLayout->addLayout(formLayout);
         mainLayout->addWidget(buttonBox);

         connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
         connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
         connect(nameText, &QLineEdit::textChanged, this, &AddDialog::updateEnabled);
         connect(addressText, &QPlainTextEdit::textChanged, this, &AddDialog::updateEnabled);

         setWindowTitle(tr("Add a Contact"));

         updateEnabled();
     }

     void AddDialog::updateEnabled()
     {
         Contact c = contact();
         const bool valid = !c.name.isEmpty() && c.name.front().isLetter() && !c.address.isEmpty();
         buttonBox->button(QDialogButtonBox::Ok)->setEnabled(valid);
     }

     Contact AddDialog::contact() const
     {
         return { nameText->text().trimmed(), addressText->toPlainText().trimmed() };
     }

     void AddDialog::setContact(const Contact &c)
     {
         nameText->setText(c.name);
         addressText->setPlainText(c.address);
         updateEnabled();
     }

     void AddDialog::editAddress(const Contact &c)
     {
         nameText->setReadOnly(true);
         setContact(c);
     }

To give the dialog the desired behavior, we connect the OK and Cancel buttons to the dialog's accept() and reject() slots. Since the dialog only acts as a container for name and address information, we do not need to implement any other functions for it.

#### MainWindow Class Definition

The `MainWindow` class extends QMainWindow and implements the menus and actions necessary to manipulate the address book.

     class MainWindow : public QMainWindow
     {
         Q_OBJECT

     public:
         MainWindow();

     private slots:
         void updateActions(const QItemSelection &selection);
         void openFile();
         void saveFile();

     private:
         void createMenus();

         AddressWidget *addressWidget;
         QAction *editAct;
         QAction *removeAct;
     };

The `MainWindow` class uses an `AddressWidget` as its central widget and provides the File menu with Open, Close and Exit actions, as well as the Tools menu with Add Entry..., Edit Entry... and Remove Entry actions.

#### MainWindow Class Implementation

The constructor for `MainWindow` instantiates AddressWidget, sets it as its central widget and calls the `createMenus()` function.

     MainWindow::MainWindow()
         : QMainWindow(),
           addressWidget(new AddressWidget)
     {
         setCentralWidget(addressWidget);
         createMenus();
         setWindowTitle(tr("Address Book"));
     }

The `createMenus()` function sets up the File and Tools menus, connecting the actions to their respective slots. Both the Edit Entry... and Remove Entry actions are disabled by default as such actions cannot be carried out on an empty address book. They are only enabled when one or more contacts are added.

     void MainWindow::createMenus()
     {
         QMenu *fileMenu = menuBar()->addMenu(tr("&File"));

         auto *openAct = new QAction(QIcon::fromTheme(QIcon::ThemeIcon::DocumentOpen),
                                     tr("&Open..."), this);
         openAct->setShortcut(QKeySequence(QKeySequence::Open));
         fileMenu->addAction(openAct);
         connect(openAct, &QAction::triggered, this, &MainWindow::openFile);
         ...

         editAct = new QAction(tr("&Edit Entry..."), this);
         editAct->setEnabled(false);
         toolMenu->addAction(editAct);
         connect(editAct, &QAction::triggered, addressWidget, &AddressWidget::editEntry);

         toolMenu->addSeparator();

         removeAct = new QAction(tr("&Remove Entry"), this);
         removeAct->setEnabled(false);
         toolMenu->addAction(removeAct);
         connect(removeAct, &QAction::triggered, addressWidget, &AddressWidget::removeEntry);

         connect(addressWidget, &AddressWidget::selectionChanged,
                 this, &MainWindow::updateActions);
     }

Apart from connecting all the actions' signals to their respective slots, we also connect `AddressWidget`'s `selectionChanged()` signal to its `updateActions()` slot.

The `openFile()` function opens a custom `addressbook.dat` file that contains address book contacts. This function is a slot connected to `openAct` in the File menu.

     void MainWindow::openFile()
     {
         if (addressWidget->readFromFile())
             statusBar()->showMessage(tr("Read %1").arg(QDir::toNativeSeparators(AddressWidget::fileName())));
     }

The `saveFile()` function saves a custom `addressbook.dat` file that will contain the address book contacts. This function is a slot connected to `saveAct` in the File menu.

     void MainWindow::saveFile()
     {
         if (addressWidget->writeToFile())
             statusBar()->showMessage(tr("Wrote %1").arg(QDir::toNativeSeparators(AddressWidget::fileName())));
     }

The `updateActions()` function enables and disables Edit Entry... and Remove Entry depending on the contents of the address book. If the address book is empty, these actions are disabled; otherwise, they are enabled. This function is a slot is connected to the `AddressWidget`'s `selectionChanged()` signal.

     void MainWindow::updateActions(const QItemSelection &selection)
     {
         const QModelIndexList indexes = selection.indexes();

         removeAct->setEnabled(!indexes.isEmpty());
         editAct->setEnabled(!indexes.isEmpty());
     }

#### main() Function

The main function for the address book instantiates QApplication and opens a `MainWindow` before running the event loop.

     int main(int argc, char *argv[])
     {
         QApplication app(argc, argv);
         MainWindow mw;
         const auto availableGeometry = mw.screen()->availableGeometry();
         mw.resize(availableGeometry.width() / 3, availableGeometry.height() / 3);
         mw.show();
         return QCoreApplication::exec();
     }

Example project @ code.qt.io