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());
```
- 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
The default language of subsurface is US English so please use US English
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
string to be translated is associated with a context, which corresponds
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>

View file

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

View file

@ -76,11 +76,11 @@ bool CheckCloudConnection::checkServer()
return false;
}
void CheckCloudConnection::sslErrors(QList<QSslError> errorList)
void CheckCloudConnection::sslErrors(const QList<QSslError> &errorList)
{
if (verbose) {
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();
}
}

View file

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

View file

@ -81,11 +81,11 @@ void CloudStorageAuthenticate::uploadError(QNetworkReply::NetworkError)
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) {
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();
}
}

View file

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

View file

@ -341,7 +341,7 @@ dc_status_t BLEObject::setHwCredit(unsigned int c)
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
* 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.
@ -479,16 +479,16 @@ dc_status_t qt_ble_open(void **io, dc_context_t *, const char *devaddr, dc_user_
return r;
}
} else {
foreach (const QLowEnergyCharacteristic &c, list) {
for (const QLowEnergyCharacteristic &c: list) {
if (!is_read_characteristic(c))
continue;
qDebug() << "Using read characteristic" << c.uuid();
QList<QLowEnergyDescriptor> l = c.descriptors();
const QList<QLowEnergyDescriptor> l = c.descriptors();
QLowEnergyDescriptor d = l.first();
foreach (const QLowEnergyDescriptor &tmp, l) {
for (const QLowEnergyDescriptor &tmp: l) {
if (tmp.type() == QBluetoothUuid::ClientCharacteristicConfiguration) {
d = tmp;
break;

View file

@ -35,7 +35,7 @@ public slots:
void characteristcStateChanged(const QLowEnergyCharacteristic &c, const QByteArray &value);
void characteristicWritten(const QLowEnergyCharacteristic &c, 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);
private:
QVector<QLowEnergyService *> services;

View file

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

View file

@ -75,11 +75,11 @@ void LocationInformationWidget::mergeSelectedDiveSites()
QMessageBox::Ok, QMessageBox::Cancel) != QMessageBox::Ok)
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<struct dive_site *> selected_dive_sites;
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 *>();
if (ds)
selected_dive_sites.push_back(ds);

View file

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

View file

@ -21,9 +21,9 @@ TabDiveStatistics::TabDiveStatistics(QWidget *parent) : TabBase(parent), ui(new
ui->timeLimits->overrideMinToolTipText(tr("Shortest dive"));
ui->timeLimits->overrideAvgToolTipText(tr("Average length of all selected dives"));
Q_FOREACH (QObject *obj, children()) {
if (QLabel *label = qobject_cast<QLabel *>(obj))
label->setAlignment(Qt::AlignHCenter);
const auto l = findChildren<QLabel *>(QString(), Qt::FindDirectChildrenOnly);
for (QLabel *label: l) {
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)
{
QStringList displayedList, currentList;
currentList = currentString.split(',', QString::SkipEmptyParts);
displayedList = displayedString.split(',', QString::SkipEmptyParts);
Q_FOREACH ( const QString tag, currentList) {
const QStringList currentList = currentString.split(',', QString::SkipEmptyParts);
const QStringList displayedList = displayedString.split(',', QString::SkipEmptyParts);
for (const QString &tag: currentList) {
if (!displayedList.contains(tag, Qt::CaseInsensitive))
removedList << tag.trimmed();
}
Q_FOREACH (const QString tag, displayedList) {
for (const QString &tag: displayedList) {
if (!currentList.contains(tag, Qt::CaseInsensitive))
addedList << tag.trimmed();
}

View file

@ -70,7 +70,8 @@ void TagWidget::highlight()
{
removeAllBlocks();
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();
if (trimmed.isEmpty())
continue;

View file

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

View file

@ -599,7 +599,7 @@ void QMLManager::handleSslErrors(const QList<QSslError> &errors)
{
auto *reply = qobject_cast<QNetworkReply *>(sender());
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());
}
reply->abort();
@ -1761,8 +1761,8 @@ void QMLManager::setStatusbarColor(QColor)
void QMLManager::retrieveBluetoothName()
{
QString name = DC_devName();
QList<BTDiscovery::btVendorProduct> btDCs = BTDiscovery::instance()->getBtDcs();
foreach (BTDiscovery::btVendorProduct btDC, btDCs) {
const QList<BTDiscovery::btVendorProduct> btDCs = BTDiscovery::instance()->getBtDcs();
for (BTDiscovery::btVendorProduct btDC: btDCs) {
qDebug() << "compare" <<name << btDC.btpdi.address;
if (name.contains(btDC.btpdi.address))
DC_setDevBluetoothName(btDC.btpdi.name);

View file

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

View file

@ -1101,9 +1101,9 @@ bool ProfileWidget2::eventFilter(QObject *object, QEvent *event)
#endif
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);
}

View file

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

View file

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

View file

@ -76,8 +76,8 @@ void run_ui()
// 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 Contents/Frameworks/qml and make sure that we add the correct import path
QStringList importPathList = engine.importPathList();
Q_FOREACH (QString importPath, importPathList) {
const QStringList importPathList = engine.importPathList();
for (QString importPath: importPathList) {
if (importPath.contains("MacOS"))
engine.addImportPath(importPath.replace("MacOS", "Frameworks"));
}