get rid of some foreach and Q_FOREACH constructs

See https://www.kdab.com/goodbye-q_foreach/

This is reduced to the places where the container is const or can be made const
without the need to always introduce an extra variable. Sadly qAsConst (Qt 5.7)
and std::as_const (C++17) are not available in all supported setups.

Also do some minor cleanups along the way.

Signed-off-by: Rolf Eike Beer <eike@sf-mail.de>
This commit is contained in:
Rolf Eike Beer 2019-04-01 22:15:19 +02:00 committed by Dirk Hohndel
parent 2b9ca488fd
commit c4c8094e32
21 changed files with 62 additions and 49 deletions

View file

@ -156,6 +156,16 @@ other editors that implement this coding style, please add them here.
``` ```
QLowEnergyService *service = qobject_cast<QLowEnergyService*>(sender()); QLowEnergyService *service = qobject_cast<QLowEnergyService*>(sender());
``` ```
- If the variable is a container that is only assigned to a local variable to
be able to use it in a range-based for loop
```
const auto l = device.serviceUuids();
for (QBluetoothUuid id: serviceUuids) {
```
The variable has also to be const to avoid that Qt containers will do a
deep copy when the range bases for loop will call the begin() method
internally.
* text strings * text strings
The default language of subsurface is US English so please use US English The default language of subsurface is US English so please use US English
spelling and terminology. spelling and terminology.
@ -173,7 +183,7 @@ other editors that implement this coding style, please add them here.
This works by default in classes (indirectly) derived from QObject. Each This works by default in classes (indirectly) derived from QObject. Each
string to be translated is associated with a context, which corresponds string to be translated is associated with a context, which corresponds
to the class name. Classes that are not derived from QObject can generate to the class name. Classes that are not derived from QObject can generate
the tr() functions by using the `Q_DECLARE_FUNCTIONS` macro: the tr() functions by using the `Q_DECLARE_TR_FUNCTIONS` macro:
``` ```
#include <QCoreApplication> #include <QCoreApplication>

View file

@ -198,8 +198,8 @@ void BTDiscovery::btDeviceDiscovered(const QBluetoothDeviceInfo &device)
this_d.name = device.name(); this_d.name = device.name();
btPairedDevices.append(this_d); btPairedDevices.append(this_d);
QList<QBluetoothUuid> serviceUuids = device.serviceUuids(); const auto serviceUuids = device.serviceUuids();
foreach (QBluetoothUuid id, serviceUuids) { for (QBluetoothUuid id: serviceUuids) {
addBtUuid(id); addBtUuid(id);
qDebug() << id.toByteArray(); qDebug() << id.toByteArray();
} }

View file

@ -76,11 +76,11 @@ bool CheckCloudConnection::checkServer()
return false; return false;
} }
void CheckCloudConnection::sslErrors(QList<QSslError> errorList) void CheckCloudConnection::sslErrors(const QList<QSslError> &errorList)
{ {
if (verbose) { if (verbose) {
qDebug() << "Received error response trying to set up https connection with cloud storage backend:"; qDebug() << "Received error response trying to set up https connection with cloud storage backend:";
Q_FOREACH (QSslError err, errorList) { for (QSslError err: errorList) {
qDebug() << err.errorString(); qDebug() << err.errorString();
} }
} }

View file

@ -15,7 +15,7 @@ private:
QNetworkReply *reply; QNetworkReply *reply;
private private
slots: slots:
void sslErrors(QList<QSslError> errorList); void sslErrors(const QList<QSslError> &errorList);
}; };
#endif // CHECKCLOUDCONNECTION_H #endif // CHECKCLOUDCONNECTION_H

View file

@ -81,11 +81,11 @@ void CloudStorageAuthenticate::uploadError(QNetworkReply::NetworkError)
qDebug() << "Received error response from cloud storage backend:" << reply->errorString(); qDebug() << "Received error response from cloud storage backend:" << reply->errorString();
} }
void CloudStorageAuthenticate::sslErrors(QList<QSslError> errorList) void CloudStorageAuthenticate::sslErrors(const QList<QSslError> &errorList)
{ {
if (verbose) { if (verbose) {
qDebug() << "Received error response trying to set up https connection with cloud storage backend:"; qDebug() << "Received error response trying to set up https connection with cloud storage backend:";
Q_FOREACH (QSslError err, errorList) { for (QSslError err: errorList) {
qDebug() << err.errorString(); qDebug() << err.errorString();
} }
} }

View file

@ -16,7 +16,7 @@ signals:
private private
slots: slots:
void uploadError(QNetworkReply::NetworkError error); void uploadError(QNetworkReply::NetworkError error);
void sslErrors(QList<QSslError> errorList); void sslErrors(const QList<QSslError> &errorList);
void uploadFinished(); void uploadFinished();
private: private:
QNetworkReply *reply; QNetworkReply *reply;

View file

@ -341,7 +341,7 @@ dc_status_t BLEObject::setHwCredit(unsigned int c)
return DC_STATUS_SUCCESS; return DC_STATUS_SUCCESS;
} }
dc_status_t BLEObject::setupHwTerminalIo(QList<QLowEnergyCharacteristic> allC) dc_status_t BLEObject::setupHwTerminalIo(const QList<QLowEnergyCharacteristic> &allC)
{ /* This initalizes the Terminal I/O client as described in { /* This initalizes the Terminal I/O client as described in
* http://www.telit.com/fileadmin/user_upload/products/Downloads/sr-rf/BlueMod/TIO_Implementation_Guide_r04.pdf * http://www.telit.com/fileadmin/user_upload/products/Downloads/sr-rf/BlueMod/TIO_Implementation_Guide_r04.pdf
* Referenced section numbers below are from that document. * Referenced section numbers below are from that document.
@ -479,16 +479,16 @@ dc_status_t qt_ble_open(void **io, dc_context_t *, const char *devaddr, dc_user_
return r; return r;
} }
} else { } else {
foreach (const QLowEnergyCharacteristic &c, list) { for (const QLowEnergyCharacteristic &c: list) {
if (!is_read_characteristic(c)) if (!is_read_characteristic(c))
continue; continue;
qDebug() << "Using read characteristic" << c.uuid(); qDebug() << "Using read characteristic" << c.uuid();
QList<QLowEnergyDescriptor> l = c.descriptors(); const QList<QLowEnergyDescriptor> l = c.descriptors();
QLowEnergyDescriptor d = l.first(); QLowEnergyDescriptor d = l.first();
foreach (const QLowEnergyDescriptor &tmp, l) { for (const QLowEnergyDescriptor &tmp: l) {
if (tmp.type() == QBluetoothUuid::ClientCharacteristicConfiguration) { if (tmp.type() == QBluetoothUuid::ClientCharacteristicConfiguration) {
d = tmp; d = tmp;
break; break;

View file

@ -35,7 +35,7 @@ public slots:
void characteristcStateChanged(const QLowEnergyCharacteristic &c, const QByteArray &value); void characteristcStateChanged(const QLowEnergyCharacteristic &c, const QByteArray &value);
void characteristicWritten(const QLowEnergyCharacteristic &c, const QByteArray &value); void characteristicWritten(const QLowEnergyCharacteristic &c, const QByteArray &value);
void writeCompleted(const QLowEnergyDescriptor &d, const QByteArray &value); void writeCompleted(const QLowEnergyDescriptor &d, const QByteArray &value);
dc_status_t setupHwTerminalIo(QList<QLowEnergyCharacteristic>); dc_status_t setupHwTerminalIo(const QList<QLowEnergyCharacteristic> &allC);
dc_status_t setHwCredit(unsigned int c); dc_status_t setHwCredit(unsigned int c);
private: private:
QVector<QLowEnergyService *> services; QVector<QLowEnergyService *> services;

View file

@ -1144,7 +1144,7 @@ QStringList imageExtensionFilters()
QStringList videoExtensionFilters() QStringList videoExtensionFilters()
{ {
QStringList filters; QStringList filters;
foreach (const QString &format, videoExtensionsList) for (const QString &format: videoExtensionsList)
filters.append("*" + format); filters.append("*" + format);
return filters; return filters;
} }
@ -1506,9 +1506,9 @@ int parse_seabear_header(const char *filename, char **params, int pnr)
parseLine = f.readLine().trimmed(); parseLine = f.readLine().trimmed();
QStringList currColumns = parseLine.split(';'); const QStringList currColumns = parseLine.split(';');
unsigned short index = 0; unsigned short index = 0;
Q_FOREACH (QString columnText, currColumns) { for (const QString &columnText: currColumns) {
if (columnText == "Time") { if (columnText == "Time") {
params[pnr++] = strdup("timeField"); params[pnr++] = strdup("timeField");
params[pnr++] = intdup(index++); params[pnr++] = intdup(index++);

View file

@ -75,11 +75,11 @@ void LocationInformationWidget::mergeSelectedDiveSites()
QMessageBox::Ok, QMessageBox::Cancel) != QMessageBox::Ok) QMessageBox::Ok, QMessageBox::Cancel) != QMessageBox::Ok)
return; return;
QModelIndexList selection = ui.diveSiteListView->selectionModel()->selectedIndexes(); const QModelIndexList selection = ui.diveSiteListView->selectionModel()->selectedIndexes();
// std::vector guarantees contiguous storage and can therefore be passed to C-code // std::vector guarantees contiguous storage and can therefore be passed to C-code
std::vector<struct dive_site *> selected_dive_sites; std::vector<struct dive_site *> selected_dive_sites;
selected_dive_sites.reserve(selection.count()); selected_dive_sites.reserve(selection.count());
Q_FOREACH (const QModelIndex &idx, selection) { for (const QModelIndex &idx: selection) {
dive_site *ds = idx.data(LocationInformationModel::DIVESITE_ROLE).value<dive_site *>(); dive_site *ds = idx.data(LocationInformationModel::DIVESITE_ROLE).value<dive_site *>();
if (ds) if (ds)
selected_dive_sites.push_back(ds); selected_dive_sites.push_back(ds);

View file

@ -77,8 +77,8 @@ void Printer::flowRender()
// get all references to dontbreak divs // get all references to dontbreak divs
int start = 0, end = 0; int start = 0, end = 0;
int fullPageResolution = webView->page()->mainFrame()->contentsSize().height(); int fullPageResolution = webView->page()->mainFrame()->contentsSize().height();
QWebElementCollection dontbreak = webView->page()->mainFrame()->findAllElements(".dontbreak"); const QWebElementCollection dontbreak = webView->page()->mainFrame()->findAllElements(".dontbreak");
foreach (QWebElement dontbreakElement, dontbreak) { for (QWebElement dontbreakElement: dontbreak) {
if ((dontbreakElement.geometry().y() + dontbreakElement.geometry().height()) - start < pageSize.height()) { if ((dontbreakElement.geometry().y() + dontbreakElement.geometry().height()) - start < pageSize.height()) {
// One more element can be placed // One more element can be placed
end = dontbreakElement.geometry().y() + dontbreakElement.geometry().height(); end = dontbreakElement.geometry().y() + dontbreakElement.geometry().height();

View file

@ -21,8 +21,8 @@ TabDiveStatistics::TabDiveStatistics(QWidget *parent) : TabBase(parent), ui(new
ui->timeLimits->overrideMinToolTipText(tr("Shortest dive")); ui->timeLimits->overrideMinToolTipText(tr("Shortest dive"));
ui->timeLimits->overrideAvgToolTipText(tr("Average length of all selected dives")); ui->timeLimits->overrideAvgToolTipText(tr("Average length of all selected dives"));
Q_FOREACH (QObject *obj, children()) { const auto l = findChildren<QLabel *>(QString(), Qt::FindDirectChildrenOnly);
if (QLabel *label = qobject_cast<QLabel *>(obj)) for (QLabel *label: l) {
label->setAlignment(Qt::AlignHCenter); label->setAlignment(Qt::AlignHCenter);
} }
} }

View file

@ -1271,14 +1271,13 @@ void MainTab::saveTaggedStrings(const QVector<dive *> &selectedDives)
int MainTab::diffTaggedStrings(QString currentString, QString displayedString, QStringList &addedList, QStringList &removedList) int MainTab::diffTaggedStrings(QString currentString, QString displayedString, QStringList &addedList, QStringList &removedList)
{ {
QStringList displayedList, currentList; const QStringList currentList = currentString.split(',', QString::SkipEmptyParts);
currentList = currentString.split(',', QString::SkipEmptyParts); const QStringList displayedList = displayedString.split(',', QString::SkipEmptyParts);
displayedList = displayedString.split(',', QString::SkipEmptyParts); for (const QString &tag: currentList) {
Q_FOREACH ( const QString tag, currentList) {
if (!displayedList.contains(tag, Qt::CaseInsensitive)) if (!displayedList.contains(tag, Qt::CaseInsensitive))
removedList << tag.trimmed(); removedList << tag.trimmed();
} }
Q_FOREACH (const QString tag, displayedList) { for (const QString &tag: displayedList) {
if (!currentList.contains(tag, Qt::CaseInsensitive)) if (!currentList.contains(tag, Qt::CaseInsensitive))
addedList << tag.trimmed(); addedList << tag.trimmed();
} }

View file

@ -70,7 +70,8 @@ void TagWidget::highlight()
{ {
removeAllBlocks(); removeAllBlocks();
int lastPos = 0; int lastPos = 0;
Q_FOREACH (const QString& s, text().split(QChar(','), QString::SkipEmptyParts)) { const auto l = text().split(QChar(','), QString::SkipEmptyParts);
for (const QString &s: l) {
QString trimmed = s.trimmed(); QString trimmed = s.trimmed();
if (trimmed.isEmpty()) if (trimmed.isEmpty())
continue; continue;

View file

@ -19,20 +19,20 @@ int getTotalWork(print_options *printOptions)
void find_all_templates() void find_all_templates()
{ {
const QString ext(".html"); const QLatin1String ext(".html");
grantlee_templates.clear(); grantlee_templates.clear();
grantlee_statistics_templates.clear(); grantlee_statistics_templates.clear();
QDir dir(getPrintingTemplatePathUser()); QDir dir(getPrintingTemplatePathUser());
QStringList list = dir.entryList(QDir::Files | QDir::NoDotAndDotDot); const QStringList list = dir.entryList(QDir::Files | QDir::NoDotAndDotDot);
foreach (const QString& filename, list) { for (const QString &filename: list) {
if (filename.at(filename.size() - 1) != '~' && filename.endsWith(ext)) if (filename.at(filename.size() - 1) != '~' && filename.endsWith(ext))
grantlee_templates.append(filename); grantlee_templates.append(filename);
} }
// find statistics templates // find statistics templates
dir.setPath(getPrintingTemplatePathUser() + QDir::separator() + "statistics"); dir.setPath(getPrintingTemplatePathUser() + QDir::separator() + "statistics");
list = dir.entryList(QDir::Files | QDir::NoDotAndDotDot); const QStringList stat = dir.entryList(QDir::Files | QDir::NoDotAndDotDot);
foreach (const QString& filename, list) { for (const QString &filename: stat) {
if (filename.at(filename.size() - 1) != '~' && filename.endsWith(ext)) if (filename.at(filename.size() - 1) != '~' && filename.endsWith(ext))
grantlee_statistics_templates.append(filename); grantlee_statistics_templates.append(filename);
} }
@ -66,12 +66,14 @@ void copy_bundled_templates(QString src, QString dst, QStringList *templateBacku
QDir dir(src); QDir dir(src);
if (!dir.exists()) if (!dir.exists())
return; return;
foreach (QString d, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) { const auto dirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
for (const QString &d: dirs) {
QString dst_path = dst + QDir::separator() + d; QString dst_path = dst + QDir::separator() + d;
dir.mkpath(dst_path); dir.mkpath(dst_path);
copy_bundled_templates(src + QDir::separator() + d, dst_path, templateBackupList); copy_bundled_templates(src + QDir::separator() + d, dst_path, templateBackupList);
} }
foreach (QString f, dir.entryList(QDir::Files)) { const auto files = dir.entryList(QDir::Files);
for (const QString &f: files) {
QFile fileSrc(src + QDir::separator() + f); QFile fileSrc(src + QDir::separator() + f);
QFile fileDest(dst + QDir::separator() + f); QFile fileDest(dst + QDir::separator() + f);
if (fileDest.exists()) { if (fileDest.exists()) {

View file

@ -599,7 +599,7 @@ void QMLManager::handleSslErrors(const QList<QSslError> &errors)
{ {
auto *reply = qobject_cast<QNetworkReply *>(sender()); auto *reply = qobject_cast<QNetworkReply *>(sender());
setStartPageText(RED_FONT + tr("Cannot open cloud storage: Error creating https connection") + END_FONT); setStartPageText(RED_FONT + tr("Cannot open cloud storage: Error creating https connection") + END_FONT);
Q_FOREACH (QSslError e, errors) { for (QSslError e: errors) {
appendTextToLog(e.errorString()); appendTextToLog(e.errorString());
} }
reply->abort(); reply->abort();
@ -1761,8 +1761,8 @@ void QMLManager::setStatusbarColor(QColor)
void QMLManager::retrieveBluetoothName() void QMLManager::retrieveBluetoothName()
{ {
QString name = DC_devName(); QString name = DC_devName();
QList<BTDiscovery::btVendorProduct> btDCs = BTDiscovery::instance()->getBtDcs(); const QList<BTDiscovery::btVendorProduct> btDCs = BTDiscovery::instance()->getBtDcs();
foreach (BTDiscovery::btVendorProduct btDC, btDCs) { for (BTDiscovery::btVendorProduct btDC: btDCs) {
qDebug() << "compare" <<name << btDC.btpdi.address; qDebug() << "compare" <<name << btDC.btpdi.address;
if (name.contains(btDC.btpdi.address)) if (name.contains(btDC.btpdi.address))
DC_setDevBluetoothName(btDC.btpdi.name); DC_setDevBluetoothName(btDC.btpdi.name);

View file

@ -272,8 +272,9 @@ void ToolTipItem::refresh(const QPointF &pos)
} }
entryToolTip.first->setPixmap(tissues); entryToolTip.first->setPixmap(tissues);
Q_FOREACH (QGraphicsItem *item, scene()->items(pos, Qt::IntersectsItemBoundingRect const auto l = scene()->items(pos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder,
,Qt::DescendingOrder, scene()->views().first()->transform())) { scene()->views().first()->transform());
for (QGraphicsItem *item: l) {
if (!item->toolTip().isEmpty()) if (!item->toolTip().isEmpty())
addToolTip(item->toolTip()); addToolTip(item->toolTip());
} }

View file

@ -1101,9 +1101,9 @@ bool ProfileWidget2::eventFilter(QObject *object, QEvent *event)
#endif #endif
template <typename T> template <typename T>
static void hideAll(T &container) static void hideAll(const T &container)
{ {
Q_FOREACH (auto *item, container) for (auto *item: container)
item->setVisible(false); item->setVisible(false);
} }

View file

@ -144,12 +144,12 @@ DiveListModel::DiveListModel(QObject *parent) : QAbstractListModel(parent)
m_instance = this; m_instance = this;
} }
void DiveListModel::addDive(QList<dive *>listOfDives) void DiveListModel::addDive(const QList<dive *> &listOfDives)
{ {
if (listOfDives.isEmpty()) if (listOfDives.isEmpty())
return; return;
beginInsertRows(QModelIndex(), rowCount(), rowCount() + listOfDives.count() - 1); beginInsertRows(QModelIndex(), rowCount(), rowCount() + listOfDives.count() - 1);
foreach (dive *d, listOfDives) { for (dive *d: listOfDives) {
m_dives.append(new DiveObjectHelper(d)); m_dives.append(new DiveObjectHelper(d));
} }
endInsertRows(); endInsertRows();

View file

@ -44,7 +44,7 @@ public:
static DiveListModel *instance(); static DiveListModel *instance();
DiveListModel(QObject *parent = 0); DiveListModel(QObject *parent = 0);
void addDive(QList<dive *> listOfDives); void addDive(const QList<dive *> &listOfDives);
void addAllDives(); void addAllDives();
void insertDive(int i, DiveObjectHelper *newDive); void insertDive(int i, DiveObjectHelper *newDive);
void removeDive(int i); void removeDive(int i);

View file

@ -76,8 +76,8 @@ void run_ui()
// same directory the executable was started from <bundle>/Contents/MacOS/ // same directory the executable was started from <bundle>/Contents/MacOS/
// To work around this we need to manually copy the components at install time // To work around this we need to manually copy the components at install time
// to Contents/Frameworks/qml and make sure that we add the correct import path // to Contents/Frameworks/qml and make sure that we add the correct import path
QStringList importPathList = engine.importPathList(); const QStringList importPathList = engine.importPathList();
Q_FOREACH (QString importPath, importPathList) { for (QString importPath: importPathList) {
if (importPath.contains("MacOS")) if (importPath.contains("MacOS"))
engine.addImportPath(importPath.replace("MacOS", "Frameworks")); engine.addImportPath(importPath.replace("MacOS", "Frameworks"));
} }