QtWidgets: replace some index-based for loops with C++11 range-for

This needs to be handled a bit carefully, because Qt containers
will detach upon being iteratoed over using range-for.

In the cases of this patch, that cannot happen, because all
containers are marked as const (either by this patch or before).

Separate patches will deal with other situations.

Apart from being more readable, range-for loops are also the
most efficient for loop.

This patch shaves almost 2K of text size off an optimized Linux
AMD64 GCC 4.9 build.

Change-Id: I53810c7b25420b4fd449d20c90c07503c5e76a66
Reviewed-by: Edward Welbourne <edward.welbourne@theqtcompany.com>
Reviewed-by: Lars Knoll <lars.knoll@theqtcompany.com>
This commit is contained in:
Marc Mutz 2015-11-30 12:19:31 +01:00
parent b697518634
commit 0516487237
22 changed files with 138 additions and 170 deletions

View File

@ -53,10 +53,9 @@ QT_BEGIN_NAMESPACE
static QList<QWidget*> childWidgets(const QWidget *widget) static QList<QWidget*> childWidgets(const QWidget *widget)
{ {
QList<QObject*> list = widget->children();
QList<QWidget*> widgets; QList<QWidget*> widgets;
for (int i = 0; i < list.size(); ++i) { for (QObject *o : widget->children()) {
QWidget *w = qobject_cast<QWidget *>(list.at(i)); QWidget *w = qobject_cast<QWidget *>(o);
if (w && !w->isWindow() if (w && !w->isWindow()
&& !qobject_cast<QFocusFrame*>(w) && !qobject_cast<QFocusFrame*>(w)
#if !defined(QT_NO_MENU) #if !defined(QT_NO_MENU)
@ -77,9 +76,8 @@ static QString buddyString(const QWidget *widget)
if (!parent) if (!parent)
return QString(); return QString();
#ifndef QT_NO_SHORTCUT #ifndef QT_NO_SHORTCUT
QObjectList ol = parent->children(); for (QObject *o : parent->children()) {
for (int i = 0; i < ol.size(); ++i) { QLabel *label = qobject_cast<QLabel*>(o);
QLabel *label = qobject_cast<QLabel*>(ol.at(i));
if (label && label->buddy() == widget) if (label && label->buddy() == widget)
return label->text(); return label->text();
} }
@ -302,8 +300,8 @@ QAccessibleWidget::relations(QAccessible::Relation match /*= QAccessible::AllRel
// ideally we would go through all objects and check, but that // ideally we would go through all objects and check, but that
// will be too expensive // will be too expensive
const QList<QWidget*> kids = childWidgets(parent); const QList<QWidget*> kids = childWidgets(parent);
for (int i = 0; i < kids.count(); ++i) { for (QWidget *kid : kids) {
if (QLabel *labelSibling = qobject_cast<QLabel*>(kids.at(i))) { if (QLabel *labelSibling = qobject_cast<QLabel*>(kid)) {
if (labelSibling->buddy() == widget()) { if (labelSibling->buddy() == widget()) {
QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(labelSibling); QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(labelSibling);
rels.append(qMakePair(iface, rel)); rels.append(qMakePair(iface, rel));

View File

@ -71,10 +71,9 @@ QList<QWidget*> childWidgets(const QWidget *widget)
{ {
if (widget == 0) if (widget == 0)
return QList<QWidget*>(); return QList<QWidget*>();
QList<QObject*> list = widget->children();
QList<QWidget*> widgets; QList<QWidget*> widgets;
for (int i = 0; i < list.size(); ++i) { for (QObject *o : widget->children()) {
QWidget *w = qobject_cast<QWidget *>(list.at(i)); QWidget *w = qobject_cast<QWidget *>(o);
if (!w) if (!w)
continue; continue;
QString objectName = w->objectName(); QString objectName = w->objectName();
@ -1056,10 +1055,9 @@ QAccessibleInterface *QAccessibleMainWindow::childAt(int x, int y) const
if (!QRect(gp.x(), gp.y(), w->width(), w->height()).contains(x, y)) if (!QRect(gp.x(), gp.y(), w->width(), w->height()).contains(x, y))
return 0; return 0;
QWidgetList kids = childWidgets(mainWindow()); const QWidgetList kids = childWidgets(mainWindow());
QPoint rp = mainWindow()->mapFromGlobal(QPoint(x, y)); QPoint rp = mainWindow()->mapFromGlobal(QPoint(x, y));
for (int i = 0; i < kids.size(); ++i) { for (QWidget *child : kids) {
QWidget *child = kids.at(i);
if (!child->isWindow() && !child->isHidden() && child->geometry().contains(rp)) { if (!child->isWindow() && !child->isHidden() && child->geometry().contains(rp)) {
return QAccessible::queryAccessibleInterface(child); return QAccessible::queryAccessibleInterface(child);
} }

View File

@ -570,8 +570,8 @@ QAccessibleGroupBox::relations(QAccessible::Relation match /* = QAccessible::All
if ((match & QAccessible::Labelled) && (!groupBox()->title().isEmpty())) { if ((match & QAccessible::Labelled) && (!groupBox()->title().isEmpty())) {
const QList<QWidget*> kids = childWidgets(widget()); const QList<QWidget*> kids = childWidgets(widget());
for (int i = 0; i < kids.count(); ++i) { for (QWidget *kid : kids) {
QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(kids.at(i)); QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(kid);
if (iface) if (iface)
rels.append(qMakePair(iface, QAccessible::Relation(QAccessible::Labelled))); rels.append(qMakePair(iface, QAccessible::Relation(QAccessible::Labelled)));
} }

View File

@ -2587,7 +2587,7 @@ void QFileDialog::accept()
return; return;
} }
QStringList files = selectedFiles(); const QStringList files = selectedFiles();
if (files.isEmpty()) if (files.isEmpty())
return; return;
QString lineEditText = d->lineEdit()->text(); QString lineEditText = d->lineEdit()->text();
@ -2657,10 +2657,10 @@ void QFileDialog::accept()
case ExistingFile: case ExistingFile:
case ExistingFiles: case ExistingFiles:
for (int i = 0; i < files.count(); ++i) { for (const auto &file : files) {
QFileInfo info(files.at(i)); QFileInfo info(file);
if (!info.exists()) if (!info.exists())
info = QFileInfo(d->getEnvironmentVariable(files.at(i))); info = QFileInfo(d->getEnvironmentVariable(file));
if (!info.exists()) { if (!info.exists()) {
#ifndef QT_NO_MESSAGEBOX #ifndef QT_NO_MESSAGEBOX
QString message = tr("%1\nFile not found.\nPlease verify the " QString message = tr("%1\nFile not found.\nPlease verify the "
@ -3444,15 +3444,13 @@ void QFileDialogPrivate::_q_autoCompleteFileName(const QString &text)
return; return;
} }
QStringList multipleFiles = typedFiles(); const QStringList multipleFiles = typedFiles();
if (multipleFiles.count() > 0) { if (multipleFiles.count() > 0) {
QModelIndexList oldFiles = qFileDialogUi->listView->selectionModel()->selectedRows(); QModelIndexList oldFiles = qFileDialogUi->listView->selectionModel()->selectedRows();
QModelIndexList newFiles; QModelIndexList newFiles;
for (int i = 0; i < multipleFiles.count(); ++i) { for (const auto &file : multipleFiles) {
QModelIndex idx = model->index(multipleFiles.at(i)); QModelIndex idx = model->index(file);
if (oldFiles.contains(idx)) if (oldFiles.removeAll(idx) == 0)
oldFiles.removeAll(idx);
else
newFiles.append(idx); newFiles.append(idx);
} }
for (int i = 0; i < newFiles.count(); ++i) for (int i = 0; i < newFiles.count(); ++i)
@ -3479,7 +3477,7 @@ void QFileDialogPrivate::_q_updateOkButton()
bool enableButton = true; bool enableButton = true;
bool isOpenDirectory = false; bool isOpenDirectory = false;
QStringList files = q->selectedFiles(); const QStringList files = q->selectedFiles();
QString lineEditText = lineEdit()->text(); QString lineEditText = lineEdit()->text();
if (lineEditText.startsWith(QLatin1String("//")) || lineEditText.startsWith(QLatin1Char('\\'))) { if (lineEditText.startsWith(QLatin1String("//")) || lineEditText.startsWith(QLatin1Char('\\'))) {
@ -3538,10 +3536,10 @@ void QFileDialogPrivate::_q_updateOkButton()
} }
case QFileDialog::ExistingFile: case QFileDialog::ExistingFile:
case QFileDialog::ExistingFiles: case QFileDialog::ExistingFiles:
for (int i = 0; i < files.count(); ++i) { for (const auto &file : files) {
QModelIndex idx = model->index(files.at(i)); QModelIndex idx = model->index(file);
if (!idx.isValid()) if (!idx.isValid())
idx = model->index(getEnvironmentVariable(files.at(i))); idx = model->index(getEnvironmentVariable(file));
if (!idx.isValid()) { if (!idx.isValid()) {
enableButton = false; enableButton = false;
break; break;
@ -3682,14 +3680,14 @@ void QFileDialogPrivate::_q_useNameFilter(int index)
void QFileDialogPrivate::_q_selectionChanged() void QFileDialogPrivate::_q_selectionChanged()
{ {
const QFileDialog::FileMode fileMode = q_func()->fileMode(); const QFileDialog::FileMode fileMode = q_func()->fileMode();
QModelIndexList indexes = qFileDialogUi->listView->selectionModel()->selectedRows(); const QModelIndexList indexes = qFileDialogUi->listView->selectionModel()->selectedRows();
bool stripDirs = (fileMode != QFileDialog::DirectoryOnly && fileMode != QFileDialog::Directory); bool stripDirs = (fileMode != QFileDialog::DirectoryOnly && fileMode != QFileDialog::Directory);
QStringList allFiles; QStringList allFiles;
for (int i = 0; i < indexes.count(); ++i) { for (const auto &index : indexes) {
if (stripDirs && model->isDir(mapToSource(indexes.at(i)))) if (stripDirs && model->isDir(mapToSource(index)))
continue; continue;
allFiles.append(indexes.at(i).data().toString()); allFiles.append(index.data().toString());
} }
if (allFiles.count() > 1) if (allFiles.count() > 1)
for (int i = 0; i < allFiles.count(); ++i) { for (int i = 0; i < allFiles.count(); ++i) {

View File

@ -282,8 +282,8 @@ void QFileInfoGatherer::getFileInfos(const QString &path, const QStringList &fil
infoList = QDir::drives(); infoList = QDir::drives();
} else { } else {
infoList.reserve(files.count()); infoList.reserve(files.count());
for (int i = 0; i < files.count(); ++i) for (const auto &file : files)
infoList << QFileInfo(files.at(i)); infoList << QFileInfo(file);
} }
for (int i = infoList.count() - 1; i >= 0; --i) { for (int i = infoList.count() - 1; i >= 0; --i) {
QString driveName = translateDriveName(infoList.at(i)); QString driveName = translateDriveName(infoList.at(i));

View File

@ -1562,10 +1562,9 @@ void QFileSystemModel::setNameFilters(const QStringList &filters)
d->bypassFilters.clear(); d->bypassFilters.clear();
// We guarantee that rootPath will stick around // We guarantee that rootPath will stick around
QPersistentModelIndex root(index(rootPath())); QPersistentModelIndex root(index(rootPath()));
QModelIndexList persistantList = persistentIndexList(); const QModelIndexList persistentList = persistentIndexList();
for (int i = 0; i < persistantList.count(); ++i) { for (const auto &persistentIndex : persistentList) {
QFileSystemModelPrivate::QFileSystemNode *node; QFileSystemModelPrivate::QFileSystemNode *node = d->node(persistentIndex);
node = d->node(persistantList.at(i));
while (node) { while (node) {
if (d->bypassFilters.contains(node)) if (d->bypassFilters.contains(node))
break; break;
@ -1579,9 +1578,8 @@ void QFileSystemModel::setNameFilters(const QStringList &filters)
d->nameFilters.clear(); d->nameFilters.clear();
const Qt::CaseSensitivity caseSensitive = const Qt::CaseSensitivity caseSensitive =
(filter() & QDir::CaseSensitive) ? Qt::CaseSensitive : Qt::CaseInsensitive; (filter() & QDir::CaseSensitive) ? Qt::CaseSensitive : Qt::CaseInsensitive;
for (int i = 0; i < filters.size(); ++i) { for (const auto &filter : filters)
d->nameFilters << QRegExp(filters.at(i), caseSensitive, QRegExp::Wildcard); d->nameFilters << QRegExp(filter, caseSensitive, QRegExp::Wildcard);
}
d->forceSort = true; d->forceSort = true;
d->delayedSort(); d->delayedSort();
#endif #endif
@ -1734,9 +1732,9 @@ void QFileSystemModelPrivate::addVisibleFiles(QFileSystemNode *parentNode, const
if (parentNode->dirtyChildrenIndex == -1) if (parentNode->dirtyChildrenIndex == -1)
parentNode->dirtyChildrenIndex = parentNode->visibleChildren.count(); parentNode->dirtyChildrenIndex = parentNode->visibleChildren.count();
for (int i = 0; i < newFiles.count(); ++i) { for (const auto &newFile : newFiles) {
parentNode->visibleChildren.append(newFiles.at(i)); parentNode->visibleChildren.append(newFile);
parentNode->children.value(newFiles.at(i))->isVisible = true; parentNode->children.value(newFile)->isVisible = true;
} }
if (!indexHidden) if (!indexHidden)
q->endInsertRows(); q->endInsertRows();
@ -1779,10 +1777,10 @@ void QFileSystemModelPrivate::_q_fileSystemChanged(const QString &path, const QV
QStringList newFiles; QStringList newFiles;
QFileSystemModelPrivate::QFileSystemNode *parentNode = node(path, false); QFileSystemModelPrivate::QFileSystemNode *parentNode = node(path, false);
QModelIndex parentIndex = index(parentNode); QModelIndex parentIndex = index(parentNode);
for (int i = 0; i < updates.count(); ++i) { for (const auto &update : updates) {
QString fileName = updates.at(i).first; QString fileName = update.first;
Q_ASSERT(!fileName.isEmpty()); Q_ASSERT(!fileName.isEmpty());
QExtendedInformation info = fileInfoGatherer.getInfo(updates.at(i).second); QExtendedInformation info = fileInfoGatherer.getInfo(update.second);
bool previouslyHere = parentNode->children.contains(fileName); bool previouslyHere = parentNode->children.contains(fileName);
if (!previouslyHere) { if (!previouslyHere) {
addNode(parentNode, fileName, info.fileInfo()); addNode(parentNode, fileName, info.fileInfo());
@ -1971,8 +1969,8 @@ bool QFileSystemModelPrivate::passNameFilters(const QFileSystemNode *node) const
// Check the name regularexpression filters // Check the name regularexpression filters
if (!(node->isDir() && (filters & QDir::AllDirs))) { if (!(node->isDir() && (filters & QDir::AllDirs))) {
for (int i = 0; i < nameFilters.size(); ++i) { for (const auto &nameFilter : nameFilters) {
QRegExp copy = nameFilters.at(i); QRegExp copy = nameFilter;
if (copy.exactMatch(node->fileName)) if (copy.exactMatch(node->fileName))
return true; return true;
} }

View File

@ -1047,26 +1047,26 @@ void QMessageBoxPrivate::detectEscapeButton()
} }
// if the message box has one RejectRole button, make it the escape button // if the message box has one RejectRole button, make it the escape button
for (int i = 0; i < buttons.count(); i++) { for (auto *button : buttons) {
if (buttonBox->buttonRole(buttons.at(i)) == QDialogButtonBox::RejectRole) { if (buttonBox->buttonRole(button) == QDialogButtonBox::RejectRole) {
if (detectedEscapeButton) { // already detected! if (detectedEscapeButton) { // already detected!
detectedEscapeButton = 0; detectedEscapeButton = 0;
break; break;
} }
detectedEscapeButton = buttons.at(i); detectedEscapeButton = button;
} }
} }
if (detectedEscapeButton) if (detectedEscapeButton)
return; return;
// if the message box has one NoRole button, make it the escape button // if the message box has one NoRole button, make it the escape button
for (int i = 0; i < buttons.count(); i++) { for (auto *button : buttons) {
if (buttonBox->buttonRole(buttons.at(i)) == QDialogButtonBox::NoRole) { if (buttonBox->buttonRole(button) == QDialogButtonBox::NoRole) {
if (detectedEscapeButton) { // already detected! if (detectedEscapeButton) { // already detected!
detectedEscapeButton = 0; detectedEscapeButton = 0;
break; break;
} }
detectedEscapeButton = buttons.at(i); detectedEscapeButton = button;
} }
} }
} }
@ -1506,8 +1506,7 @@ void QMessageBox::keyPressEvent(QKeyEvent *e)
int key = e->key() & ~Qt::MODIFIER_MASK; int key = e->key() & ~Qt::MODIFIER_MASK;
if (key) { if (key) {
const QList<QAbstractButton *> buttons = d->buttonBox->buttons(); const QList<QAbstractButton *> buttons = d->buttonBox->buttons();
for (int i = 0; i < buttons.count(); ++i) { for (auto *pb : buttons) {
QAbstractButton *pb = buttons.at(i);
QKeySequence shortcut = pb->shortcut(); QKeySequence shortcut = pb->shortcut();
if (!shortcut.isEmpty() && key == int(shortcut[0] & ~Qt::MODIFIER_MASK)) { if (!shortcut.isEmpty() && key == int(shortcut[0] & ~Qt::MODIFIER_MASK)) {
pb->animateClick(); pb->animateClick();

View File

@ -103,9 +103,9 @@ Qt::ItemFlags QUrlModel::flags(const QModelIndex &index) const
QMimeData *QUrlModel::mimeData(const QModelIndexList &indexes) const QMimeData *QUrlModel::mimeData(const QModelIndexList &indexes) const
{ {
QList<QUrl> list; QList<QUrl> list;
for (int i = 0; i < indexes.count(); ++i) { for (const auto &index : indexes) {
if (indexes.at(i).column() == 0) if (index.column() == 0)
list.append(indexes.at(i).data(UrlRole).toUrl()); list.append(index.data(UrlRole).toUrl());
} }
QMimeData *data = new QMimeData(); QMimeData *data = new QMimeData();
data->setUrls(list); data->setUrls(list);
@ -125,8 +125,8 @@ bool QUrlModel::canDrop(QDragEnterEvent *event)
return false; return false;
const QList<QUrl> list = event->mimeData()->urls(); const QList<QUrl> list = event->mimeData()->urls();
for (int i = 0; i < list.count(); ++i) { for (const auto &url : list) {
QModelIndex idx = fileSystemModel->index(list.at(0).toLocalFile()); const QModelIndex idx = fileSystemModel->index(url.toLocalFile());
if (!fileSystemModel->isDir(idx)) if (!fileSystemModel->isDir(idx))
return false; return false;
} }

View File

@ -3622,9 +3622,8 @@ void QWizardPage::cleanupPage()
{ {
Q_D(QWizardPage); Q_D(QWizardPage);
if (d->wizard) { if (d->wizard) {
QVector<QWizardField> &fields = d->wizard->d_func()->fields; const QVector<QWizardField> &fields = d->wizard->d_func()->fields;
for (int i = 0; i < fields.count(); ++i) { for (const auto &field : fields) {
const QWizardField &field = fields.at(i);
if (field.page == this) if (field.page == this)
field.object->setProperty(field.property, field.initialValue); field.object->setProperty(field.property, field.initialValue);
} }

View File

@ -222,9 +222,8 @@ public:
QSet<Vertex *> setOfVertices = vertices(); QSet<Vertex *> setOfVertices = vertices();
for (typename QSet<Vertex*>::const_iterator it = setOfVertices.begin(); it != setOfVertices.end(); ++it) { for (typename QSet<Vertex*>::const_iterator it = setOfVertices.begin(); it != setOfVertices.end(); ++it) {
Vertex *v = *it; Vertex *v = *it;
QList<Vertex*> adjacents = adjacentVertices(v); const QList<Vertex*> adjacents = adjacentVertices(v);
for (int i = 0; i < adjacents.count(); ++i) { for (auto *v1 : adjacents) {
Vertex *v1 = adjacents.at(i);
EdgeData *data = edgeData(v, v1); EdgeData *data = edgeData(v, v1);
bool forward = data->from == v; bool forward = data->from == v;
if (forward) { if (forward) {

View File

@ -4351,8 +4351,7 @@ QItemViewPaintPairs QAbstractItemViewPrivate::draggablePaintPairs(const QModelIn
QRect &rect = *r; QRect &rect = *r;
const QRect viewportRect = viewport->rect(); const QRect viewportRect = viewport->rect();
QItemViewPaintPairs ret; QItemViewPaintPairs ret;
for (int i = 0; i < indexes.count(); ++i) { for (const auto &index : indexes) {
const QModelIndex &index = indexes.at(i);
const QRect current = q->visualRect(index); const QRect current = q->visualRect(index);
if (current.intersects(viewportRect)) { if (current.intersects(viewportRect)) {
QItemViewPaintPair p = { current, index }; QItemViewPaintPair p = { current, index };

View File

@ -177,9 +177,10 @@ public:
// Whether the data can actually be dropped will be checked in drag move. // Whether the data can actually be dropped will be checked in drag move.
if (event->type() == QEvent::DragEnter && (event->dropAction() & model->supportedDropActions())) { if (event->type() == QEvent::DragEnter && (event->dropAction() & model->supportedDropActions())) {
const QStringList modelTypes = model->mimeTypes(); const QStringList modelTypes = model->mimeTypes();
for (int i = 0; i < modelTypes.count(); ++i) for (const auto &modelType : modelTypes) {
if (mime->hasFormat(modelTypes.at(i))) if (mime->hasFormat(modelType))
return true; return true;
}
} }
QModelIndex index; QModelIndex index;

View File

@ -169,8 +169,8 @@ void QDirModelPrivate::invalidate()
const QDirNode *current = nodes.pop(); const QDirNode *current = nodes.pop();
current->stat = false; current->stat = false;
const QVector<QDirNode> &children = current->children; const QVector<QDirNode> &children = current->children;
for (int i = 0; i < children.count(); ++i) for (const auto &child : children)
nodes.push(&children.at(i)); nodes.push(&child);
} }
} }

View File

@ -2958,8 +2958,7 @@ QRegion QHeaderView::visualRegionForSelection(const QItemSelection &selection) c
int right = 0; int right = 0;
int rangeLeft, rangeRight; int rangeLeft, rangeRight;
for (int i = 0; i < selection.count(); ++i) { for (const auto &r : selection) {
QItemSelectionRange r = selection.at(i);
if (r.parent().isValid() || !r.isValid()) if (r.parent().isValid() || !r.isValid())
continue; // we only know about toplevel items and we don't want invalid ranges continue; // we only know about toplevel items and we don't want invalid ranges
// FIXME an item inside the range may be the leftmost or rightmost // FIXME an item inside the range may be the leftmost or rightmost
@ -2992,8 +2991,7 @@ QRegion QHeaderView::visualRegionForSelection(const QItemSelection &selection) c
int bottom = 0; int bottom = 0;
int rangeTop, rangeBottom; int rangeTop, rangeBottom;
for (int i = 0; i < selection.count(); ++i) { for (const auto &r : selection) {
QItemSelectionRange r = selection.at(i);
if (r.parent().isValid() || !r.isValid()) if (r.parent().isValid() || !r.isValid())
continue; // we only know about toplevel items continue; // we only know about toplevel items
// FIXME an item inside the range may be the leftmost or rightmost // FIXME an item inside the range may be the leftmost or rightmost

View File

@ -327,8 +327,8 @@ public:
inline int headerLength() const { // for debugging inline int headerLength() const { // for debugging
int len = 0; int len = 0;
for (int i = 0; i < sectionItems.count(); ++i) for (const auto &section : sectionItems)
len += sectionItems.at(i).size; len += section.size;
return len; return len;
} }

View File

@ -651,8 +651,7 @@ QItemViewPaintPairs QListViewPrivate::draggablePaintPairs(const QModelIndexList
const QRect viewportRect = viewport->rect(); const QRect viewportRect = viewport->rect();
QItemViewPaintPairs ret; QItemViewPaintPairs ret;
const QSet<QModelIndex> visibleIndexes = intersectingSet(viewportRect.translated(q->horizontalOffset(), q->verticalOffset())).toList().toSet(); const QSet<QModelIndex> visibleIndexes = intersectingSet(viewportRect.translated(q->horizontalOffset(), q->verticalOffset())).toList().toSet();
for (int i = 0; i < indexes.count(); ++i) { for (const auto &index : indexes) {
const QModelIndex &index = indexes.at(i);
if (visibleIndexes.contains(index)) { if (visibleIndexes.contains(index)) {
const QRect current = q->visualRect(index); const QRect current = q->visualRect(index);
QItemViewPaintPair p = { current, index }; QItemViewPaintPair p = { current, index };
@ -1398,16 +1397,16 @@ QRegion QListView::visualRegionForSelection(const QItemSelection &selection) con
int c = d->column; int c = d->column;
QRegion selectionRegion; QRegion selectionRegion;
const QRect &viewportRect = d->viewport->rect(); const QRect &viewportRect = d->viewport->rect();
for (int i = 0; i < selection.count(); ++i) { for (const auto &elem : selection) {
if (!selection.at(i).isValid()) if (!elem.isValid())
continue; continue;
QModelIndex parent = selection.at(i).topLeft().parent(); QModelIndex parent = elem.topLeft().parent();
//we only display the children of the root in a listview //we only display the children of the root in a listview
//we're not interested in the other model indexes //we're not interested in the other model indexes
if (parent != d->root) if (parent != d->root)
continue; continue;
int t = selection.at(i).topLeft().row(); int t = elem.topLeft().row();
int b = selection.at(i).bottomRight().row(); int b = elem.bottomRight().row();
if (d->viewMode == IconMode || d->isWrapping()) { // in non-static mode, we have to go through all selected items if (d->viewMode == IconMode || d->isWrapping()) { // in non-static mode, we have to go through all selected items
for (int r = t; r <= b; ++r) { for (int r = t; r <= b; ++r) {
const QRect &rect = visualRect(d->model->index(r, c, parent)); const QRect &rect = visualRect(d->model->index(r, c, parent));
@ -2771,9 +2770,8 @@ bool QIconModeViewBase::filterDropEvent(QDropEvent *e)
} }
QPoint start = dd->pressedPosition; QPoint start = dd->pressedPosition;
QPoint delta = (dd->movement == QListView::Snap ? snapToGrid(end) - snapToGrid(start) : end - start); QPoint delta = (dd->movement == QListView::Snap ? snapToGrid(end) - snapToGrid(start) : end - start);
QList<QModelIndex> indexes = dd->selectionModel->selectedIndexes(); const QList<QModelIndex> indexes = dd->selectionModel->selectedIndexes();
for (int i = 0; i < indexes.count(); ++i) { for (const auto &index : indexes) {
QModelIndex index = indexes.at(i);
QRect rect = dd->rectForIndex(index); QRect rect = dd->rectForIndex(index);
viewport()->update(dd->mapToViewport(rect, false)); viewport()->update(dd->mapToViewport(rect, false));
QPoint dest = rect.topLeft() + delta; QPoint dest = rect.topLeft() + delta;

View File

@ -1370,9 +1370,6 @@ void QTableView::paintEvent(QPaintEvent *event)
uint x = horizontalHeader->length() - horizontalHeader->offset() - (rightToLeft ? 0 : 1); uint x = horizontalHeader->length() - horizontalHeader->offset() - (rightToLeft ? 0 : 1);
uint y = verticalHeader->length() - verticalHeader->offset() - 1; uint y = verticalHeader->length() - verticalHeader->offset() - 1;
const QRegion region = event->region().translated(offset);
const QVector<QRect> rects = region.rects();
//firstVisualRow is the visual index of the first visible row. lastVisualRow is the visual index of the last visible Row. //firstVisualRow is the visual index of the first visible row. lastVisualRow is the visual index of the last visible Row.
//same goes for ...VisualColumn //same goes for ...VisualColumn
int firstVisualRow = qMax(verticalHeader->visualIndexAt(0),0); int firstVisualRow = qMax(verticalHeader->visualIndexAt(0),0);
@ -1391,13 +1388,15 @@ void QTableView::paintEvent(QPaintEvent *event)
QBitArray drawn((lastVisualRow - firstVisualRow + 1) * (lastVisualColumn - firstVisualColumn + 1)); QBitArray drawn((lastVisualRow - firstVisualRow + 1) * (lastVisualColumn - firstVisualColumn + 1));
const QRegion region = event->region().translated(offset);
if (d->hasSpans()) { if (d->hasSpans()) {
d->drawAndClipSpans(region, &painter, option, &drawn, d->drawAndClipSpans(region, &painter, option, &drawn,
firstVisualRow, lastVisualRow, firstVisualColumn, lastVisualColumn); firstVisualRow, lastVisualRow, firstVisualColumn, lastVisualColumn);
} }
for (int i = 0; i < rects.size(); ++i) { const QVector<QRect> rects = region.rects();
QRect dirtyArea = rects.at(i); for (auto dirtyArea : rects) {
dirtyArea.setBottom(qMin(dirtyArea.bottom(), int(y))); dirtyArea.setBottom(qMin(dirtyArea.bottom(), int(y)));
if (rightToLeft) { if (rightToLeft) {
dirtyArea.setLeft(qMax(dirtyArea.left(), d->viewport->width() - int(x))); dirtyArea.setLeft(qMax(dirtyArea.left(), d->viewport->width() - int(x)));
@ -1952,8 +1951,7 @@ QRegion QTableView::visualRegionForSelection(const QItemSelection &selection) co
bool horizontalMoved = horizontalHeader()->sectionsMoved(); bool horizontalMoved = horizontalHeader()->sectionsMoved();
if ((verticalMoved && horizontalMoved) || (d->hasSpans() && (verticalMoved || horizontalMoved))) { if ((verticalMoved && horizontalMoved) || (d->hasSpans() && (verticalMoved || horizontalMoved))) {
for (int i = 0; i < selection.count(); ++i) { for (const auto &range : selection) {
QItemSelectionRange range = selection.at(i);
if (range.parent() != d->root || !range.isValid()) if (range.parent() != d->root || !range.isValid())
continue; continue;
for (int r = range.top(); r <= range.bottom(); ++r) for (int r = range.top(); r <= range.bottom(); ++r)
@ -1964,8 +1962,7 @@ QRegion QTableView::visualRegionForSelection(const QItemSelection &selection) co
} }
} }
} else if (horizontalMoved) { } else if (horizontalMoved) {
for (int i = 0; i < selection.count(); ++i) { for (const auto &range : selection) {
QItemSelectionRange range = selection.at(i);
if (range.parent() != d->root || !range.isValid()) if (range.parent() != d->root || !range.isValid())
continue; continue;
int top = rowViewportPosition(range.top()); int top = rowViewportPosition(range.top());
@ -1980,8 +1977,7 @@ QRegion QTableView::visualRegionForSelection(const QItemSelection &selection) co
} }
} }
} else if (verticalMoved) { } else if (verticalMoved) {
for (int i = 0; i < selection.count(); ++i) { for (const auto &range : selection) {
QItemSelectionRange range = selection.at(i);
if (range.parent() != d->root || !range.isValid()) if (range.parent() != d->root || !range.isValid())
continue; continue;
int left = columnViewportPosition(range.left()); int left = columnViewportPosition(range.left());
@ -1997,8 +1993,7 @@ QRegion QTableView::visualRegionForSelection(const QItemSelection &selection) co
} }
} else { // nothing moved } else { // nothing moved
const int gridAdjust = showGrid() ? 1 : 0; const int gridAdjust = showGrid() ? 1 : 0;
for (int i = 0; i < selection.count(); ++i) { for (auto range : selection) {
QItemSelectionRange range = selection.at(i);
if (range.parent() != d->root || !range.isValid()) if (range.parent() != d->root || !range.isValid())
continue; continue;
d->trimHiddenSelections(&range); d->trimHiddenSelections(&range);

View File

@ -1388,9 +1388,10 @@ void QTableWidgetItem::setData(int role, const QVariant &value)
QVariant QTableWidgetItem::data(int role) const QVariant QTableWidgetItem::data(int role) const
{ {
role = (role == Qt::EditRole ? Qt::DisplayRole : role); role = (role == Qt::EditRole ? Qt::DisplayRole : role);
for (int i = 0; i < values.count(); ++i) for (const auto &value : values) {
if (values.at(i).role == role) if (value.role == role)
return values.at(i).value; return value.value;
}
return QVariant(); return QVariant();
} }
@ -2359,10 +2360,9 @@ QList<QTableWidgetSelectionRange> QTableWidget::selectedRanges() const
QList<QTableWidgetItem*> QTableWidget::selectedItems() const QList<QTableWidgetItem*> QTableWidget::selectedItems() const
{ {
Q_D(const QTableWidget); Q_D(const QTableWidget);
QModelIndexList indexes = selectionModel()->selectedIndexes(); const QModelIndexList indexes = selectionModel()->selectedIndexes();
QList<QTableWidgetItem*> items; QList<QTableWidgetItem*> items;
for (int i = 0; i < indexes.count(); ++i) { for (const auto &index : indexes) {
QModelIndex index = indexes.at(i);
if (isIndexHidden(index)) if (isIndexHidden(index))
continue; continue;
QTableWidgetItem *item = d->tableModel()->item(index); QTableWidgetItem *item = d->tableModel()->item(index);
@ -2682,22 +2682,21 @@ void QTableWidget::dropEvent(QDropEvent *event) {
int col = -1; int col = -1;
int row = -1; int row = -1;
if (d->dropOn(event, &row, &col, &topIndex)) { if (d->dropOn(event, &row, &col, &topIndex)) {
QModelIndexList indexes = selectedIndexes(); const QModelIndexList indexes = selectedIndexes();
int top = INT_MAX; int top = INT_MAX;
int left = INT_MAX; int left = INT_MAX;
for (int i = 0; i < indexes.count(); ++i) { for (const auto &index : indexes) {
top = qMin(indexes.at(i).row(), top); top = qMin(index.row(), top);
left = qMin(indexes.at(i).column(), left); left = qMin(index.column(), left);
} }
QList<QTableWidgetItem *> taken; QList<QTableWidgetItem *> taken;
const int indexesCount = indexes.count(); const int indexesCount = indexes.count();
taken.reserve(indexesCount); taken.reserve(indexesCount);
for (int i = 0; i < indexesCount; ++i) for (const auto &index : indexes)
taken.append(takeItem(indexes.at(i).row(), indexes.at(i).column())); taken.append(takeItem(index.row(), index.column()));
for (int i = 0; i < indexes.count(); ++i) { for (const auto &index : indexes) {
QModelIndex index = indexes.at(i);
int r = index.row() - top + topIndex.row(); int r = index.row() - top + topIndex.row();
int c = index.column() - left + topIndex.column(); int c = index.column() - left + topIndex.column();
setItem(r, c, taken.takeFirst()); setItem(r, c, taken.takeFirst());

View File

@ -2393,8 +2393,7 @@ QRegion QTreeView::visualRegionForSelection(const QItemSelection &selection) con
QRegion selectionRegion; QRegion selectionRegion;
const QRect &viewportRect = d->viewport->rect(); const QRect &viewportRect = d->viewport->rect();
for (int i = 0; i < selection.count(); ++i) { for (const auto &range : selection) {
QItemSelectionRange range = selection.at(i);
if (!range.isValid()) if (!range.isValid())
continue; continue;
QModelIndex parent = range.parent(); QModelIndex parent = range.parent();

View File

@ -725,9 +725,9 @@ QMimeData *QTreeModel::internalMimeData() const
QMimeData *QTreeModel::mimeData(const QModelIndexList &indexes) const QMimeData *QTreeModel::mimeData(const QModelIndexList &indexes) const
{ {
QList<QTreeWidgetItem*> items; QList<QTreeWidgetItem*> items;
for (int i = 0; i < indexes.count(); ++i) { for (const auto &index : indexes) {
if (indexes.at(i).column() == 0) // only one item per row if (index.column() == 0) // only one item per row
items << item(indexes.at(i)); items << item(index);
} }
// cachedIndexes is a little hack to avoid copying from QModelIndexList to // cachedIndexes is a little hack to avoid copying from QModelIndexList to
@ -1735,7 +1735,7 @@ void QTreeWidgetItem::setData(int column, int role, const QVariant &value)
default: default:
if (column < values.count()) { if (column < values.count()) {
bool found = false; bool found = false;
QVector<QWidgetItemData> column_values = values.at(column); const QVector<QWidgetItemData> column_values = values.at(column);
for (int i = 0; i < column_values.count(); ++i) { for (int i = 0; i < column_values.count(); ++i) {
if (column_values.at(i).role == role) { if (column_values.at(i).role == role) {
if (column_values.at(i).value == value) if (column_values.at(i).value == value)
@ -1785,9 +1785,10 @@ QVariant QTreeWidgetItem::data(int column, int role) const
default: default:
if (column >= 0 && column < values.size()) { if (column >= 0 && column < values.size()) {
const QVector<QWidgetItemData> &column_values = values.at(column); const QVector<QWidgetItemData> &column_values = values.at(column);
for (int i = 0; i < column_values.count(); ++i) for (const auto &column_value : column_values) {
if (column_values.at(i).role == role) if (column_value.role == role)
return column_values.at(i).value; return column_value.value;
}
} }
} }
return QVariant(); return QVariant();
@ -2136,8 +2137,8 @@ QVariant QTreeWidgetItem::childrenCheckState(int column) const
return QVariant(); return QVariant();
bool checkedChildren = false; bool checkedChildren = false;
bool uncheckedChildren = false; bool uncheckedChildren = false;
for (int i = 0; i < children.count(); ++i) { for (const auto *child : children) {
QVariant value = children.at(i)->data(column, Qt::CheckStateRole); QVariant value = child->data(column, Qt::CheckStateRole);
if (!value.isValid()) if (!value.isValid())
return QVariant(); return QVariant();
@ -3018,13 +3019,13 @@ void QTreeWidget::setItemSelected(const QTreeWidgetItem *item, bool select)
QList<QTreeWidgetItem*> QTreeWidget::selectedItems() const QList<QTreeWidgetItem*> QTreeWidget::selectedItems() const
{ {
Q_D(const QTreeWidget); Q_D(const QTreeWidget);
QModelIndexList indexes = selectionModel()->selectedIndexes(); const QModelIndexList indexes = selectionModel()->selectedIndexes();
QList<QTreeWidgetItem*> items; QList<QTreeWidgetItem*> items;
items.reserve(indexes.count()); items.reserve(indexes.count());
QSet<QTreeWidgetItem *> seen; QSet<QTreeWidgetItem *> seen;
seen.reserve(indexes.count()); seen.reserve(indexes.count());
for (int i = 0; i < indexes.count(); ++i) { for (const auto &index : indexes) {
QTreeWidgetItem *item = d->item(indexes.at(i)); QTreeWidgetItem *item = d->item(index);
if (isItemHidden(item) || seen.contains(item)) if (isItemHidden(item) || seen.contains(item))
continue; continue;
seen.insert(item); seen.insert(item);
@ -3278,8 +3279,7 @@ QMimeData *QTreeWidget::mimeData(const QList<QTreeWidgetItem*> items) const
Q_D(const QTreeWidget); Q_D(const QTreeWidget);
if (d->treeModel()->cachedIndexes.isEmpty()) { if (d->treeModel()->cachedIndexes.isEmpty()) {
QList<QModelIndex> indexes; QList<QModelIndex> indexes;
for (int i = 0; i < items.count(); ++i) { for (const auto *item : items) {
QTreeWidgetItem *item = items.at(i);
if (Q_UNLIKELY(!item)) { if (Q_UNLIKELY(!item)) {
qWarning("QTreeWidget::mimeData: Null-item passed"); qWarning("QTreeWidget::mimeData: Null-item passed");
return 0; return 0;
@ -3382,12 +3382,12 @@ void QTreeWidget::dropEvent(QDropEvent *event) {
int col = -1; int col = -1;
int row = -1; int row = -1;
if (d->dropOn(event, &row, &col, &topIndex)) { if (d->dropOn(event, &row, &col, &topIndex)) {
QList<QModelIndex> idxs = selectedIndexes(); const QList<QModelIndex> idxs = selectedIndexes();
QList<QPersistentModelIndex> indexes; QList<QPersistentModelIndex> indexes;
const int indexesCount = idxs.count(); const int indexesCount = idxs.count();
indexes.reserve(indexesCount); indexes.reserve(indexesCount);
for (int i = 0; i < indexesCount; i++) for (const auto &idx : idxs)
indexes.append(idxs.at(i)); indexes.append(idx);
if (indexes.contains(topIndex)) if (indexes.contains(topIndex))
return; return;
@ -3397,12 +3397,12 @@ void QTreeWidget::dropEvent(QDropEvent *event) {
// Remove the items // Remove the items
QList<QTreeWidgetItem *> taken; QList<QTreeWidgetItem *> taken;
for (int i = 0; i < indexes.count(); ++i) { for (const auto &index : indexes) {
QTreeWidgetItem *parent = itemFromIndex(indexes.at(i)); QTreeWidgetItem *parent = itemFromIndex(index);
if (!parent || !parent->parent()) { if (!parent || !parent->parent()) {
taken.append(takeTopLevelItem(indexes.at(i).row())); taken.append(takeTopLevelItem(index.row()));
} else { } else {
taken.append(parent->parent()->takeChild(indexes.at(i).row())); taken.append(parent->parent()->takeChild(index.row()));
} }
} }

View File

@ -1125,9 +1125,9 @@ QStyle *QApplication::style()
QStyle *&app_style = QApplicationPrivate::app_style; QStyle *&app_style = QApplicationPrivate::app_style;
app_style = QStyleFactory::create(style); app_style = QStyleFactory::create(style);
if (!app_style) { if (!app_style) {
QStringList styles = QStyleFactory::keys(); const QStringList styles = QStyleFactory::keys();
for (int i = 0; i < styles.size(); ++i) { for (const auto &style : styles) {
if ((app_style = QStyleFactory::create(styles.at(i)))) if ((app_style = QStyleFactory::create(style)))
break; break;
} }
} }
@ -1742,8 +1742,7 @@ void QApplicationPrivate::notifyWindowIconChanged()
QWindowList windowList = QGuiApplication::topLevelWindows(); QWindowList windowList = QGuiApplication::topLevelWindows();
// send to all top-level QWidgets // send to all top-level QWidgets
for (int i = 0; i < list.size(); ++i) { for (auto *w : list) {
QWidget *w = list.at(i);
windowList.removeOne(w->windowHandle()); windowList.removeOne(w->windowHandle());
QCoreApplication::sendEvent(w, &ev); QCoreApplication::sendEvent(w, &ev);
} }
@ -1906,9 +1905,8 @@ bool QApplicationPrivate::tryCloseAllWidgetWindows(QWindowList *processedWindows
} }
retry: retry:
QWidgetList list = QApplication::topLevelWidgets(); const QWidgetList list = QApplication::topLevelWidgets();
for (int i = 0; i < list.size(); ++i) { for (auto *w : list) {
QWidget *w = list.at(i);
if (w->isVisible() && w->windowType() != Qt::Desktop && if (w->isVisible() && w->windowType() != Qt::Desktop &&
!w->testAttribute(Qt::WA_DontShowOnScreen) && !w->data->is_closing) { !w->testAttribute(Qt::WA_DontShowOnScreen) && !w->data->is_closing) {
QWindow *window = w->windowHandle(); QWindow *window = w->windowHandle();
@ -1995,9 +1993,8 @@ bool QApplication::event(QEvent *e)
ce->accept(); ce->accept();
closeAllWindows(); closeAllWindows();
QWidgetList list = topLevelWidgets(); const QWidgetList list = topLevelWidgets();
for (int i = 0; i < list.size(); ++i) { for (auto *w : list) {
QWidget *w = list.at(i);
if (w->isVisible() && !(w->windowType() == Qt::Desktop) && !(w->windowType() == Qt::Popup) && if (w->isVisible() && !(w->windowType() == Qt::Desktop) && !(w->windowType() == Qt::Popup) &&
(!(w->windowType() == Qt::Dialog) || !w->parentWidget())) { (!(w->windowType() == Qt::Dialog) || !w->parentWidget())) {
ce->ignore(); ce->ignore();
@ -2011,9 +2008,8 @@ bool QApplication::event(QEvent *e)
} else if (e->type() == QEvent::LocaleChange) { } else if (e->type() == QEvent::LocaleChange) {
// on Windows the event propagation is taken care by the // on Windows the event propagation is taken care by the
// WM_SETTINGCHANGE event handler. // WM_SETTINGCHANGE event handler.
QWidgetList list = topLevelWidgets(); const QWidgetList list = topLevelWidgets();
for (int i = 0; i < list.size(); ++i) { for (auto *w : list) {
QWidget *w = list.at(i);
if (!(w->windowType() == Qt::Desktop)) { if (!(w->windowType() == Qt::Desktop)) {
if (!w->testAttribute(Qt::WA_SetLocale)) if (!w->testAttribute(Qt::WA_SetLocale))
w->d_func()->setLocale_helper(QLocale(), true); w->d_func()->setLocale_helper(QLocale(), true);
@ -2057,9 +2053,8 @@ bool QApplication::event(QEvent *e)
} }
if(e->type() == QEvent::LanguageChange) { if(e->type() == QEvent::LanguageChange) {
QWidgetList list = topLevelWidgets(); const QWidgetList list = topLevelWidgets();
for (int i = 0; i < list.size(); ++i) { for (auto *w : list) {
QWidget *w = list.at(i);
if (!(w->windowType() == Qt::Desktop)) if (!(w->windowType() == Qt::Desktop))
postEvent(w, new QEvent(QEvent::LanguageChange)); postEvent(w, new QEvent(QEvent::LanguageChange));
} }
@ -2085,8 +2080,7 @@ void QApplicationPrivate::notifyLayoutDirectionChange()
QWindowList windowList = QGuiApplication::topLevelWindows(); QWindowList windowList = QGuiApplication::topLevelWindows();
// send to all top-level QWidgets // send to all top-level QWidgets
for (int i = 0; i < list.size(); ++i) { for (auto *w : list) {
QWidget *w = list.at(i);
windowList.removeAll(w->windowHandle()); windowList.removeAll(w->windowHandle());
QEvent ev(QEvent::ApplicationLayoutDirectionChange); QEvent ev(QEvent::ApplicationLayoutDirectionChange);
QCoreApplication::sendEvent(w, &ev); QCoreApplication::sendEvent(w, &ev);
@ -2137,9 +2131,8 @@ void QApplication::setActiveWindow(QWidget* act)
if (QApplicationPrivate::active_window) { if (QApplicationPrivate::active_window) {
if (style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, QApplicationPrivate::active_window)) { if (style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, QApplicationPrivate::active_window)) {
QWidgetList list = topLevelWidgets(); const QWidgetList list = topLevelWidgets();
for (int i = 0; i < list.size(); ++i) { for (auto *w : list) {
QWidget *w = list.at(i);
if (w->isVisible() && w->isActiveWindow()) if (w->isVisible() && w->isActiveWindow())
toBeDeactivated.append(w); toBeDeactivated.append(w);
} }
@ -2160,9 +2153,8 @@ void QApplication::setActiveWindow(QWidget* act)
if (QApplicationPrivate::active_window) { if (QApplicationPrivate::active_window) {
if (style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, QApplicationPrivate::active_window)) { if (style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, QApplicationPrivate::active_window)) {
QWidgetList list = topLevelWidgets(); const QWidgetList list = topLevelWidgets();
for (int i = 0; i < list.size(); ++i) { for (auto *w : list) {
QWidget *w = list.at(i);
if (w->isVisible() && w->isActiveWindow()) if (w->isVisible() && w->isActiveWindow())
toBeActivated.append(w); toBeActivated.append(w);
} }

View File

@ -653,9 +653,7 @@ void QGroupBox::setChecked(bool b)
void QGroupBoxPrivate::_q_setChildrenEnabled(bool b) void QGroupBoxPrivate::_q_setChildrenEnabled(bool b)
{ {
Q_Q(QGroupBox); Q_Q(QGroupBox);
QObjectList childList = q->children(); for (QObject *o : q->children()) {
for (int i = 0; i < childList.size(); ++i) {
QObject *o = childList.at(i);
if (o->isWidgetType()) { if (o->isWidgetType()) {
QWidget *w = static_cast<QWidget *>(o); QWidget *w = static_cast<QWidget *>(o);
if (b) { if (b) {