Akonadi Contacts

addressmodel.cpp
1 /*
2  This file is part of Contact Editor.
3 
4  SPDX-FileCopyrightText: 2019 Volker Krause <[email protected]>
5 
6  SPDX-License-Identifier: LGPL-2.0-or-later
7 */
8 
9 #include "addressmodel.h"
10 
11 using namespace ContactEditor;
12 
13 AddressModel::AddressModel(QObject *parent)
14  : QAbstractListModel(parent)
15 {
16 }
17 
18 AddressModel::~AddressModel() = default;
19 
20 KContacts::Address::List AddressModel::addresses() const
21 {
22  return mAddresses;
23 }
24 
25 void AddressModel::setAddresses(const KContacts::Address::List &addresses)
26 {
27  beginResetModel();
28  mAddresses = addresses;
29  endResetModel();
30 }
31 
32 void AddressModel::addAddress(const KContacts::Address &address)
33 {
34  if (!address.isEmpty()) {
35  beginInsertRows({}, mAddresses.size(), mAddresses.size());
36  mAddresses.push_back(address);
37  endInsertRows();
38  }
39 }
40 
41 void AddressModel::replaceAddress(const KContacts::Address &address, int row)
42 {
43  if (row < 0 || row >= mAddresses.size()) {
44  return;
45  }
46 
47  mAddresses[row] = address;
48  Q_EMIT dataChanged(index(row, 0), index(row, 0));
49 }
50 
51 void AddressModel::removeAddress(int row)
52 {
53  if (row < 0 || row >= mAddresses.size()) {
54  return;
55  }
56 
57  beginRemoveRows({}, row, row);
58  mAddresses.remove(row);
59  endRemoveRows();
60 }
61 
62 int AddressModel::rowCount(const QModelIndex &parent) const
63 {
64  if (parent.isValid()) {
65  return 0;
66  }
67  return mAddresses.size();
68 }
69 
70 QVariant AddressModel::data(const QModelIndex &index, int role) const
71 {
72  if (!index.isValid()) {
73  return {};
74  }
75 
76  switch (role) {
77  case Qt::DisplayRole: {
78  const auto addr = mAddresses.at(index.row());
79  QString str = QLatin1String("<b>") + KContacts::Address::typeLabel(addr.type()) + QLatin1String("</b><br/>");
80  if (!addr.label().isEmpty()) {
81  str += addr.label().toHtmlEscaped().replace(QLatin1Char('\n'), QLatin1String("<br/>"));
82  } else {
83  str += addr.formattedAddress().trimmed().toHtmlEscaped().replace(QLatin1Char('\n'), QLatin1String("<br/>"));
84  }
85  return str;
86  }
87  case Qt::UserRole:
88  return QVariant::fromValue(mAddresses.at(index.row()));
89  }
90 
91  return {};
92 }
bool isValid() const const
DisplayRole
QString trimmed() const const
int row() const const
QString toHtmlEscaped() const const
QVariant fromValue(const T &value)
QString & replace(int position, int n, QChar after)
QString typeLabel() const
bool isEmpty() const
QObject * parent() const const
Q_EMITQ_EMIT
This file is part of the KDE documentation.
Documentation copyright © 1996-2021 The KDE developers.
Generated on Fri Jun 18 2021 23:08:56 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.