diff options
Diffstat (limited to 'src/widgets')
104 files changed, 1442 insertions, 1234 deletions
diff --git a/src/widgets/Qt6WidgetsMacros.cmake b/src/widgets/Qt6WidgetsMacros.cmake index aa8133ba47..b7c4392f35 100644 --- a/src/widgets/Qt6WidgetsMacros.cmake +++ b/src/widgets/Qt6WidgetsMacros.cmake @@ -36,8 +36,6 @@ # ###################################### -include(CMakeParseArguments) - # qt6_wrap_ui(outfiles inputfile ... ) diff --git a/src/widgets/accessible/complexwidgets.cpp b/src/widgets/accessible/complexwidgets.cpp index 3d5154a30f..df81713d72 100644 --- a/src/widgets/accessible/complexwidgets.cpp +++ b/src/widgets/accessible/complexwidgets.cpp @@ -177,7 +177,7 @@ QAccessibleTabBar::QAccessibleTabBar(QWidget *w) QAccessibleTabBar::~QAccessibleTabBar() { - for (QAccessible::Id id : qAsConst(m_childInterfaces)) + for (QAccessible::Id id : std::as_const(m_childInterfaces)) QAccessible::deleteAccessibleInterface(id); } @@ -320,6 +320,16 @@ int QAccessibleComboBox::indexOfChild(const QAccessibleInterface *child) const return -1; } +QAccessibleInterface *QAccessibleComboBox::focusChild() const +{ + // The editable combobox is the focus proxy of its lineedit, so the + // lineedit itself never gets focus. But it is the accessible focus + // child of an editable combobox. + if (comboBox()->isEditable()) + return child(1); + return nullptr; +} + /*! \reimp */ QString QAccessibleComboBox::text(QAccessible::Text t) const { @@ -420,7 +430,7 @@ QAccessibleInterface *QAccessibleAbstractScrollArea::child(int index) const int QAccessibleAbstractScrollArea::childCount() const { - return accessibleChildren().count(); + return accessibleChildren().size(); } int QAccessibleAbstractScrollArea::indexOfChild(const QAccessibleInterface *child) const diff --git a/src/widgets/accessible/complexwidgets_p.h b/src/widgets/accessible/complexwidgets_p.h index 1fd5d5aeeb..12535f21a0 100644 --- a/src/widgets/accessible/complexwidgets_p.h +++ b/src/widgets/accessible/complexwidgets_p.h @@ -99,6 +99,7 @@ public: QAccessibleInterface *childAt(int x, int y) const override; int indexOfChild(const QAccessibleInterface *child) const override; QAccessibleInterface* child(int index) const override; + QAccessibleInterface* focusChild() const override; QString text(QAccessible::Text t) const override; diff --git a/src/widgets/accessible/itemviews.cpp b/src/widgets/accessible/itemviews.cpp index 6da2461a6a..073f373d03 100644 --- a/src/widgets/accessible/itemviews.cpp +++ b/src/widgets/accessible/itemviews.cpp @@ -79,7 +79,7 @@ bool QAccessibleTable::isValid() const QAccessibleTable::~QAccessibleTable() { - for (QAccessible::Id id : qAsConst(childToId)) + for (QAccessible::Id id : std::as_const(childToId)) QAccessible::deleteAccessibleInterface(id); } @@ -154,21 +154,21 @@ int QAccessibleTable::selectedCellCount() const { if (!view()->selectionModel()) return 0; - return view()->selectionModel()->selectedIndexes().count(); + return view()->selectionModel()->selectedIndexes().size(); } int QAccessibleTable::selectedColumnCount() const { if (!view()->selectionModel()) return 0; - return view()->selectionModel()->selectedColumns().count(); + return view()->selectionModel()->selectedColumns().size(); } int QAccessibleTable::selectedRowCount() const { if (!view()->selectionModel()) return 0; - return view()->selectionModel()->selectedRows().count(); + return view()->selectionModel()->selectedRows().size(); } QString QAccessibleTable::rowDescription(int row) const @@ -373,7 +373,27 @@ QAccessible::Role QAccessibleTable::role() const QAccessible::State QAccessibleTable::state() const { - return QAccessible::State(); + QAccessible::State state; + const auto *w = view(); + + if (w->testAttribute(Qt::WA_WState_Visible) == false) + state.invisible = true; + if (w->focusPolicy() != Qt::NoFocus) + state.focusable = true; + if (w->hasFocus()) + state.focused = true; + if (!w->isEnabled()) + state.disabled = true; + if (w->isWindow()) { + if (w->windowFlags() & Qt::WindowSystemMenuHint) + state.movable = true; + if (w->minimumSize() != w->maximumSize()) + state.sizeable = true; + if (w->isActiveWindow()) + state.active = true; + } + + return state; } QAccessibleInterface *QAccessibleTable::childAt(int x, int y) const @@ -526,7 +546,7 @@ void QAccessibleTable::modelChange(QAccessibleTableModelChangeEvent *event) switch (event->modelChangeType()) { case QAccessibleTableModelChangeEvent::ModelReset: - for (QAccessible::Id id : qAsConst(childToId)) + for (QAccessible::Id id : std::as_const(childToId)) QAccessible::deleteAccessibleInterface(id); childToId.clear(); break; @@ -634,7 +654,7 @@ QModelIndex QAccessibleTree::indexFromLogical(int row, int column) const return QModelIndex(); const QTreeView *treeView = qobject_cast<const QTreeView*>(view()); - if (Q_UNLIKELY(row < 0 || column < 0 || treeView->d_func()->viewItems.count() <= row)) { + if (Q_UNLIKELY(row < 0 || column < 0 || treeView->d_func()->viewItems.size() <= row)) { qWarning() << "QAccessibleTree::indexFromLogical: invalid index: " << row << column << " for " << treeView; return QModelIndex(); } @@ -687,7 +707,7 @@ int QAccessibleTree::childCount() const return 0; int hHeader = horizontalHeader() ? 1 : 0; - return (treeView->d_func()->viewItems.count() + hHeader)* view()->model()->columnCount(); + return (treeView->d_func()->viewItems.size() + hHeader)* view()->model()->columnCount(); } QAccessibleInterface *QAccessibleTree::child(int logicalIndex) const @@ -723,7 +743,7 @@ int QAccessibleTree::rowCount() const { const QTreeView *treeView = qobject_cast<const QTreeView*>(view()); Q_ASSERT(treeView); - return treeView->d_func()->viewItems.count(); + return treeView->d_func()->viewItems.size(); } int QAccessibleTree::indexOfChild(const QAccessibleInterface *iface) const @@ -1004,7 +1024,7 @@ void QAccessibleTableCell::unselectCell() //one cell is selected it cannot be unselected by the user if ((selectionMode != QAbstractItemView::MultiSelection) && (selectionMode != QAbstractItemView::ExtendedSelection) - && (view->selectionModel()->selectedIndexes().count() <= 1)) + && (view->selectionModel()->selectedIndexes().size() <= 1)) return; view->selectionModel()->select(m_index, QItemSelectionModel::Deselect); diff --git a/src/widgets/accessible/qaccessiblemenu.cpp b/src/widgets/accessible/qaccessiblemenu.cpp index c193d60f10..1d72a82456 100644 --- a/src/widgets/accessible/qaccessiblemenu.cpp +++ b/src/widgets/accessible/qaccessiblemenu.cpp @@ -44,7 +44,7 @@ QMenu *QAccessibleMenu::menu() const int QAccessibleMenu::childCount() const { - return menu()->actions().count(); + return menu()->actions().size(); } QAccessibleInterface *QAccessibleMenu::childAt(int x, int y) const @@ -85,7 +85,7 @@ QAccessibleInterface *QAccessibleMenu::parent() const const QList<QObject *> associatedObjects = menuAction->associatedObjects(); parentCandidates.reserve(associatedObjects.size() + 1); parentCandidates << menu()->parentWidget() << associatedObjects; - for (QObject *object : qAsConst(parentCandidates)) { + for (QObject *object : std::as_const(parentCandidates)) { if (qobject_cast<QMenu*>(object) #if QT_CONFIG(menubar) || qobject_cast<QMenuBar*>(object) @@ -123,7 +123,7 @@ QMenuBar *QAccessibleMenuBar::menuBar() const int QAccessibleMenuBar::childCount() const { - return menuBar()->actions().count(); + return menuBar()->actions().size(); } QAccessibleInterface *QAccessibleMenuBar::child(int index) const diff --git a/src/widgets/accessible/qaccessiblewidget.cpp b/src/widgets/accessible/qaccessiblewidget.cpp index 01bdfc1ea2..13f7eca898 100644 --- a/src/widgets/accessible/qaccessiblewidget.cpp +++ b/src/widgets/accessible/qaccessiblewidget.cpp @@ -87,7 +87,7 @@ static qsizetype qt_accAmpIndex(const QString &text) qsizetype fa = 0; while ((fa = text.indexOf(u'&', fa)) != -1) { ++fa; - if (fa < text.length()) { + if (fa < text.size()) { // ignore "&&" if (text.at(fa) == u'&') { @@ -299,14 +299,14 @@ QAccessibleWidget::relations(QAccessible::Relation match /*= QAccessible::AllRel if (match & QAccessible::Controlled) { QObjectList allReceivers; QObject *connectionObject = object(); - for (int sig = 0; sig < d->primarySignals.count(); ++sig) { + for (int sig = 0; sig < d->primarySignals.size(); ++sig) { const QObjectList receivers = connectionObject->d_func()->receiverList(d->primarySignals.at(sig).toLatin1()); allReceivers += receivers; } allReceivers.removeAll(object()); //### The object might connect to itself internally - for (int i = 0; i < allReceivers.count(); ++i) { + for (int i = 0; i < allReceivers.size(); ++i) { const QAccessible::Relation rel = QAccessible::Controlled; QAccessibleInterface *iface = QAccessible::queryAccessibleInterface(allReceivers.at(i)); if (iface) diff --git a/src/widgets/accessible/qaccessiblewidgets.cpp b/src/widgets/accessible/qaccessiblewidgets.cpp index 312204e8db..7a3fd464ce 100644 --- a/src/widgets/accessible/qaccessiblewidgets.cpp +++ b/src/widgets/accessible/qaccessiblewidgets.cpp @@ -359,7 +359,7 @@ QAccessibleMdiArea::QAccessibleMdiArea(QWidget *widget) int QAccessibleMdiArea::childCount() const { - return mdiArea()->subWindowList().count(); + return mdiArea()->subWindowList().size(); } QAccessibleInterface *QAccessibleMdiArea::child(int index) const @@ -1072,7 +1072,7 @@ QAccessibleMainWindow::QAccessibleMainWindow(QWidget *widget) QAccessibleInterface *QAccessibleMainWindow::child(int index) const { QList<QWidget*> kids = childWidgets(mainWindow()); - if (index >= 0 && index < kids.count()) { + if (index >= 0 && index < kids.size()) { return QAccessible::queryAccessibleInterface(kids.at(index)); } return nullptr; @@ -1081,7 +1081,7 @@ QAccessibleInterface *QAccessibleMainWindow::child(int index) const int QAccessibleMainWindow::childCount() const { QList<QWidget*> kids = childWidgets(mainWindow()); - return kids.count(); + return kids.size(); } int QAccessibleMainWindow::indexOfChild(const QAccessibleInterface *iface) const diff --git a/src/widgets/accessible/simplewidgets.cpp b/src/widgets/accessible/simplewidgets.cpp index bb0f8401d3..d3ed74979b 100644 --- a/src/widgets/accessible/simplewidgets.cpp +++ b/src/widgets/accessible/simplewidgets.cpp @@ -673,7 +673,7 @@ QString QAccessibleLineEdit::text(QAccessible::Text t) const if (lineEdit()->echoMode() == QLineEdit::Normal) str = lineEdit()->text(); else if (lineEdit()->echoMode() != QLineEdit::NoEcho) - str = QString(lineEdit()->text().length(), QChar::fromLatin1('*')); + str = QString(lineEdit()->text().size(), QChar::fromLatin1('*')); break; default: break; @@ -779,7 +779,7 @@ void QAccessibleLineEdit::selection(int selectionIndex, int *startOffset, int *e return; *startOffset = lineEdit()->selectionStart(); - *endOffset = *startOffset + lineEdit()->selectedText().length(); + *endOffset = *startOffset + lineEdit()->selectedText().size(); } QString QAccessibleLineEdit::text(int startOffset, int endOffset) const @@ -852,7 +852,7 @@ void QAccessibleLineEdit::setSelection(int selectionIndex, int startOffset, int int QAccessibleLineEdit::characterCount() const { - return lineEdit()->text().length(); + return lineEdit()->text().size(); } void QAccessibleLineEdit::scrollToSubstring(int startIndex, int endIndex) diff --git a/src/widgets/dialogs/qfiledialog.cpp b/src/widgets/dialogs/qfiledialog.cpp index 966d86b089..05fbd072ec 100644 --- a/src/widgets/dialogs/qfiledialog.cpp +++ b/src/widgets/dialogs/qfiledialog.cpp @@ -193,7 +193,7 @@ Q_GLOBAL_STATIC(QUrl, lastVisitedDir) \value DontConfirmOverwrite Don't ask for confirmation if an existing file is selected. By default confirmation is requested. - Note: This opption is not supported on macOS when using the + Note: This option is not supported on macOS when using the native file dialog. \value DontUseNativeDialog Don't use the native file dialog. By @@ -652,7 +652,7 @@ void QFileDialogPrivate::retranslateStrings() if (proxyModel) abstractModel = proxyModel; #endif - int total = qMin(abstractModel->columnCount(QModelIndex()), actions.count() + 1); + int total = qMin(abstractModel->columnCount(QModelIndex()), actions.size() + 1); for (int i = 1; i < total; ++i) { actions.at(i - 1)->setText(QFileDialog::tr("Show ") + abstractModel->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString()); } @@ -673,7 +673,7 @@ void QFileDialogPrivate::emitFilesSelected(const QStringList &files) { Q_Q(QFileDialog); emit q->filesSelected(files); - if (files.count() == 1) + if (files.size() == 1) emit q->fileSelected(files.first()); } @@ -1357,7 +1357,7 @@ QStringList qt_strip_filters(const QStringList &filters) #if QT_CONFIG(regularexpression) QStringList strippedFilters; static const QRegularExpression r(QString::fromLatin1(QPlatformFileDialogHelper::filterRegExp)); - const int numFilters = filters.count(); + const int numFilters = filters.size(); strippedFilters.reserve(numFilters); for (int i = 0; i < numFilters; ++i) { QString filterName; @@ -1396,7 +1396,7 @@ void QFileDialog::setNameFilters(const QStringList &filters) { Q_D(QFileDialog); QStringList cleanedFilters; - const int numFilters = filters.count(); + const int numFilters = filters.size(); cleanedFilters.reserve(numFilters); for (int i = 0; i < numFilters; ++i) { cleanedFilters << filters[i].simplified(); @@ -2304,20 +2304,15 @@ void QFileDialog::getOpenFileContent(const QString &nameFilter, const std::funct openFileImpl.reset(); }; - auto qtFilterStringToWebAcceptString = [](const QString &qtString) { - // The Qt and Web name filter string formats are similar, but - // not identical. - return qtString.toStdString(); // ### TODO - }; - - QWasmLocalFileAccess::openFile(qtFilterStringToWebAcceptString(nameFilter), fileDialogClosed, acceptFile, fileContentReady); + QWasmLocalFileAccess::openFile(nameFilter.toStdString(), fileDialogClosed, + acceptFile, fileContentReady); }; (*openFileImpl)(); #else QFileDialog *dialog = new QFileDialog(); dialog->setFileMode(QFileDialog::ExistingFile); - dialog->selectNameFilter(nameFilter); + dialog->setNameFilter(nameFilter); auto fileSelected = [=](const QString &fileName) { QByteArray fileContent; @@ -2686,7 +2681,7 @@ void QFileDialog::accept() if (urls.isEmpty()) return; d->_q_emitUrlsSelected(urls); - if (urls.count() == 1) + if (urls.size() == 1) d->_q_emitUrlSelected(urls.first()); QDialog::accept(); return; @@ -2736,7 +2731,7 @@ void QFileDialog::accept() if (!info.exists()) { int maxNameLength = d->maxNameLength(info.path()); - if (maxNameLength >= 0 && info.fileName().length() > maxNameLength) + if (maxNameLength >= 0 && info.fileName().size() > maxNameLength) return; } @@ -2857,8 +2852,8 @@ bool QFileDialogPrivate::restoreWidgetState(QStringList &history, int splitterPo if (!qFileDialogUi->splitter->restoreState(splitterState)) return false; QList<int> list = qFileDialogUi->splitter->sizes(); - if (list.count() >= 2 && (list.at(0) == 0 || list.at(1) == 0)) { - for (int i = 0; i < list.count(); ++i) + if (list.size() >= 2 && (list.at(0) == 0 || list.at(1) == 0)) { + for (int i = 0; i < list.size(); ++i) list[i] = qFileDialogUi->splitter->widget(i)->sizeHint().width(); qFileDialogUi->splitter->setSizes(list); } @@ -2881,7 +2876,7 @@ bool QFileDialogPrivate::restoreWidgetState(QStringList &history, int splitterPo if (proxyModel) abstractModel = proxyModel; #endif - int total = qMin(abstractModel->columnCount(QModelIndex()), actions.count() + 1); + int total = qMin(abstractModel->columnCount(QModelIndex()), actions.size() + 1); for (int i = 1; i < total; ++i) actions.at(i - 1)->setChecked(!headerView->isSectionHidden(i)); @@ -3337,7 +3332,7 @@ void QFileDialogPrivate::_q_pathChanged(const QString &newPath) if (currentHistoryLocation < 0 || currentHistory.value(currentHistoryLocation).path != newNativePath) { if (currentHistoryLocation >= 0) saveHistorySelection(); - while (currentHistoryLocation >= 0 && currentHistoryLocation + 1 < currentHistory.count()) { + while (currentHistoryLocation >= 0 && currentHistoryLocation + 1 < currentHistory.size()) { currentHistory.removeLast(); } currentHistory.append({newNativePath, PersistentModelIndexList()}); @@ -3543,7 +3538,7 @@ void QFileDialogPrivate::_q_deleteCurrent() return; QModelIndexList list = qFileDialogUi->listView->selectionModel()->selectedRows(); - for (int i = list.count() - 1; i >= 0; --i) { + for (int i = list.size() - 1; i >= 0; --i) { QPersistentModelIndex index = list.at(i); if (index == qFileDialogUi->listView->rootIndex()) continue; @@ -3599,7 +3594,7 @@ void QFileDialogPrivate::_q_autoCompleteFileName(const QString &text) } const QStringList multipleFiles = typedFiles(); - if (multipleFiles.count() > 0) { + if (multipleFiles.size() > 0) { QModelIndexList oldFiles = qFileDialogUi->listView->selectionModel()->selectedRows(); QList<QModelIndex> newFiles; for (const auto &file : multipleFiles) { @@ -3607,11 +3602,11 @@ void QFileDialogPrivate::_q_autoCompleteFileName(const QString &text) if (oldFiles.removeAll(idx) == 0) newFiles.append(idx); } - for (const auto &newFile : qAsConst(newFiles)) + for (const auto &newFile : std::as_const(newFiles)) select(newFile); if (lineEdit()->hasFocus()) { auto *sm = qFileDialogUi->listView->selectionModel(); - for (const auto &oldFile : qAsConst(oldFiles)) + for (const auto &oldFile : std::as_const(oldFiles)) sm->select(oldFile, QItemSelectionModel::Toggle | QItemSelectionModel::Rows); } } @@ -3666,7 +3661,7 @@ void QFileDialogPrivate::_q_updateOkButton() fileDir = info.canonicalFilePath(); } else { fileDir = fn.mid(0, fn.lastIndexOf(u'/')); - fileName = fn.mid(fileDir.length() + 1); + fileName = fn.mid(fileDir.size() + 1); } if (lineEditText.contains(".."_L1)) { fileDir = info.canonicalFilePath(); @@ -3684,7 +3679,7 @@ void QFileDialogPrivate::_q_updateOkButton() } if (!idx.isValid()) { int maxLength = maxNameLength(fileDir); - enableButton = maxLength < 0 || fileName.length() <= maxLength; + enableButton = maxLength < 0 || fileName.size() <= maxLength; } break; } @@ -3807,14 +3802,14 @@ void QFileDialogPrivate::_q_useNameFilter(int index) QStringList newNameFilters = QPlatformFileDialogHelper::cleanFilterList(nameFilter); if (q_func()->acceptMode() == QFileDialog::AcceptSave) { QString newNameFilterExtension; - if (newNameFilters.count() > 0) + if (newNameFilters.size() > 0) newNameFilterExtension = QFileInfo(newNameFilters.at(0)).suffix(); QString fileName = lineEdit()->text(); const QString fileNameExtension = QFileInfo(fileName).suffix(); if (!fileNameExtension.isEmpty() && !newNameFilterExtension.isEmpty()) { - const int fileNameExtensionLength = fileNameExtension.length(); - fileName.replace(fileName.length() - fileNameExtensionLength, + const int fileNameExtensionLength = fileNameExtension.size(); + fileName.replace(fileName.size() - fileNameExtensionLength, fileNameExtensionLength, newNameFilterExtension); qFileDialogUi->listView->clearSelection(); lineEdit()->setText(fileName); @@ -3842,8 +3837,8 @@ void QFileDialogPrivate::_q_selectionChanged() continue; allFiles.append(index.data().toString()); } - if (allFiles.count() > 1) - for (qsizetype i = 0; i < allFiles.count(); ++i) { + if (allFiles.size() > 1) + for (qsizetype i = 0; i < allFiles.size(); ++i) { allFiles.replace(i, QString(u'"' + allFiles.at(i) + u'"')); } @@ -4011,12 +4006,12 @@ void QFileDialogComboBox::showPopup() // append history QList<QUrl> urls; - for (int i = 0; i < m_history.count(); ++i) { + for (int i = 0; i < m_history.size(); ++i) { QUrl path = QUrl::fromLocalFile(m_history.at(i)); if (!urls.contains(path)) urls.prepend(path); } - if (urls.count() > 0) { + if (urls.size() > 0) { model()->insertRow(model()->rowCount()); idx = model()->index(model()->rowCount()-1, 0); // ### TODO maybe add a horizontal line before this @@ -4162,12 +4157,12 @@ QString QFSCompleter::pathFromIndex(const QModelIndex &index) const if (!currentLocation.isEmpty() && path.startsWith(currentLocation)) { #if defined(Q_OS_UNIX) if (currentLocation == QDir::separator()) - return path.mid(currentLocation.length()); + return path.mid(currentLocation.size()); #endif if (currentLocation.endsWith(u'/')) - return path.mid(currentLocation.length()); + return path.mid(currentLocation.size()); else - return path.mid(currentLocation.length()+1); + return path.mid(currentLocation.size()+1); } return index.data(QFileSystemModel::FilePathRole).toString(); } @@ -4219,7 +4214,7 @@ QStringList QFSCompleter::splitPath(const QString &path) const #else bool startsFromRoot = pathCopy[0] == sep; #endif - if (parts.count() == 1 || (parts.count() > 1 && !startsFromRoot)) { + if (parts.size() == 1 || (parts.size() > 1 && !startsFromRoot)) { const QFileSystemModel *dirModel; if (proxyModel) dirModel = qobject_cast<const QFileSystemModel *>(proxyModel->sourceModel()); @@ -4232,7 +4227,7 @@ QStringList QFSCompleter::splitPath(const QString &path) const #endif if (currentLocation.contains(sep) && path != currentLocation) { QStringList currentLocationList = splitPath(currentLocation); - while (!currentLocationList.isEmpty() && parts.count() > 0 && parts.at(0) == ".."_L1) { + while (!currentLocationList.isEmpty() && parts.size() > 0 && parts.at(0) == ".."_L1) { parts.removeFirst(); currentLocationList.removeLast(); } diff --git a/src/widgets/dialogs/qmessagebox.cpp b/src/widgets/dialogs/qmessagebox.cpp index e9682440c6..7ef8ef8685 100644 --- a/src/widgets/dialogs/qmessagebox.cpp +++ b/src/widgets/dialogs/qmessagebox.cpp @@ -1031,14 +1031,14 @@ void QMessageBoxPrivate::detectEscapeButton() // If there is only one button, make it the escape button const QList<QAbstractButton *> buttons = buttonBox->buttons(); - if (buttons.count() == 1) { + if (buttons.size() == 1) { detectedEscapeButton = buttons.first(); return; } // If there are two buttons and one of them is the "Show Details..." // button, then make the other one the escape button - if (buttons.count() == 2 && detailsButton) { + if (buttons.size() == 2 && detailsButton) { auto idx = buttons.indexOf(detailsButton); if (idx != -1) { detectedEscapeButton = buttons.at(1 - idx); diff --git a/src/widgets/dialogs/qsidebar.cpp b/src/widgets/dialogs/qsidebar.cpp index bbbcb83630..8fb160ab65 100644 --- a/src/widgets/dialogs/qsidebar.cpp +++ b/src/widgets/dialogs/qsidebar.cpp @@ -211,7 +211,7 @@ void QUrlModel::addUrls(const QList<QUrl> &list, int row, bool move) if (row == -1) row = rowCount(); row = qMin(row, rowCount()); - for (int i = list.count() - 1; i >= 0; --i) { + for (int i = list.size() - 1; i >= 0; --i) { QUrl url = list.at(i); if (!url.isValid() || url.scheme() != "file"_L1) continue; @@ -291,7 +291,7 @@ void QUrlModel::setFileSystemModel(QFileSystemModel *model) void QUrlModel::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { QModelIndex parent = topLeft.parent(); - for (int i = 0; i < watching.count(); ++i) { + for (int i = 0; i < watching.size(); ++i) { QModelIndex index = watching.at(i).index; if (index.model() && topLeft.model()) { Q_ASSERT(index.model() == topLeft.model()); @@ -312,7 +312,7 @@ void QUrlModel::dataChanged(const QModelIndex &topLeft, const QModelIndex &botto void QUrlModel::layoutChanged() { QStringList paths; - const int numPaths = watching.count(); + const int numPaths = watching.size(); paths.reserve(numPaths); for (int i = 0; i < numPaths; ++i) paths.append(watching.at(i).path); @@ -417,7 +417,7 @@ void QSidebar::showContextMenu(const QPoint &position) connect(action, SIGNAL(triggered()), this, SLOT(removeEntry())); actions.append(action); } - if (actions.count() > 0) + if (actions.size() > 0) QMenu::exec(actions, mapToGlobal(position)); } #endif // QT_CONFIG(menu) @@ -431,7 +431,7 @@ void QSidebar::removeEntry() { QList<QModelIndex> idxs = selectionModel()->selectedIndexes(); QList<QPersistentModelIndex> indexes; - const int numIndexes = idxs.count(); + const int numIndexes = idxs.size(); indexes.reserve(numIndexes); for (int i = 0; i < numIndexes; i++) indexes.append(idxs.at(i)); diff --git a/src/widgets/dialogs/qwizard.cpp b/src/widgets/dialogs/qwizard.cpp index 5b95b62772..e6cce3925c 100644 --- a/src/widgets/dialogs/qwizard.cpp +++ b/src/widgets/dialogs/qwizard.cpp @@ -181,7 +181,7 @@ QWizardField::QWizardField(QWizardPage *page, const QString &spec, QObject *obje void QWizardField::resolve(const QList<QWizardDefaultProperty> &defaultPropertyTable) { if (property.isEmpty()) - findProperty(defaultPropertyTable.constData(), defaultPropertyTable.count()); + findProperty(defaultPropertyTable.constData(), defaultPropertyTable.size()); initialValue = object->property(property); } @@ -695,10 +695,10 @@ void QWizardPrivate::reset() if (current != -1) { q->currentPage()->hide(); cleanupPagesNotInHistory(); - for (int i = history.count() - 1; i >= 0; --i) + for (int i = history.size() - 1; i >= 0; --i) q->cleanupPage(history.at(i)); history.clear(); - for (QWizardPage *page : qAsConst(pageMap)) + for (QWizardPage *page : std::as_const(pageMap)) page->d_func()->initialized = false; current = -1; @@ -732,7 +732,7 @@ void QWizardPrivate::addField(const QWizardField &field) return; } - fieldIndexMap.insert(myField.name, fields.count()); + fieldIndexMap.insert(myField.name, fields.size()); fields += myField; if (myField.mandatory && !myField.changedSignal.isEmpty()) QObject::connect(myField.object, myField.changedSignal, @@ -1425,10 +1425,10 @@ void QWizardPrivate::updateButtonTexts() void QWizardPrivate::updateButtonLayout() { if (buttonsHaveCustomLayout) { - QVarLengthArray<QWizard::WizardButton, QWizard::NButtons> array(buttonsCustomLayout.count()); - for (int i = 0; i < buttonsCustomLayout.count(); ++i) + QVarLengthArray<QWizard::WizardButton, QWizard::NButtons> array(buttonsCustomLayout.size()); + for (int i = 0; i < buttonsCustomLayout.size(); ++i) array[i] = buttonsCustomLayout.at(i); - setButtonLayout(array.constData(), array.count()); + setButtonLayout(array.constData(), array.size()); } else { // Positions: // Help Stretch Custom1 Custom2 Custom3 Cancel Back Next Commit Finish Cancel Help @@ -1645,15 +1645,15 @@ void QWizardPrivate::_q_updateButtonStates() const QWizardPage *page = q->currentPage(); bool complete = page && page->isComplete(); - btn.back->setEnabled(history.count() > 1 - && !q->page(history.at(history.count() - 2))->isCommitPage() + btn.back->setEnabled(history.size() > 1 + && !q->page(history.at(history.size() - 2))->isCommitPage() && (!canFinish || !(opts & QWizard::DisabledBackButtonOnLastPage))); btn.next->setEnabled(canContinue && complete); btn.commit->setEnabled(canContinue && complete); btn.finish->setEnabled(canFinish && complete); const bool backButtonVisible = buttonLayoutContains(QWizard::BackButton) - && (history.count() > 1 || !(opts & QWizard::NoBackButtonOnStartPage)) + && (history.size() > 1 || !(opts & QWizard::NoBackButtonOnStartPage)) && (canContinue || !(opts & QWizard::NoBackButtonOnLastPage)); bool commitPage = page && page->isCommitPage(); btn.back->setVisible(backButtonVisible); @@ -2228,7 +2228,7 @@ void QWizard::setPage(int theid, QWizardPage *page) page->setParent(d->pageFrame); QList<QWizardField> &pendingFields = page->d_func()->pendingFields; - for (int i = 0; i < pendingFields.count(); ++i) + for (int i = 0; i < pendingFields.size(); ++i) d->addField(pendingFields.at(i)); pendingFields.clear(); @@ -2269,11 +2269,11 @@ void QWizard::removePage(int id) QWizardPage *removedPage = nullptr; // update startItem accordingly - if (d->pageMap.count() > 0) { // only if we have any pages + if (d->pageMap.size() > 0) { // only if we have any pages if (d->start == id) { const int firstId = d->pageMap.constBegin().key(); if (firstId == id) { - if (d->pageMap.count() > 1) + if (d->pageMap.size() > 1) d->start = (++d->pageMap.constBegin()).key(); // secondId else d->start = -1; // removing the last page @@ -2296,7 +2296,7 @@ void QWizard::removePage(int id) removedPage = d->pageMap.take(id); d->history.removeOne(id); d->_q_updateButtonStates(); - } else if (d->history.count() == 1) { + } else if (d->history.size() == 1) { // Case 3: removing the current page which is the first (and only) one in the history d->reset(); removedPage = d->pageMap.take(id); @@ -2319,7 +2319,7 @@ void QWizard::removePage(int id) d->pageVBoxLayout->removeWidget(removedPage); - for (int i = d->fields.count() - 1; i >= 0; --i) { + for (int i = d->fields.size() - 1; i >= 0; --i) { if (d->fields.at(i).page == removedPage) { removedPage->d_func()->pendingFields += d->fields.at(i); d->removeFieldAt(i); @@ -2397,7 +2397,7 @@ void QWizard::setStartId(int theid) Q_D(QWizard); int newStart = theid; if (theid == -1) - newStart = d->pageMap.count() ? d->pageMap.constBegin().key() : -1; + newStart = d->pageMap.size() ? d->pageMap.constBegin().key() : -1; if (d->start == newStart) { d->startSetByUser = theid != -1; @@ -2706,7 +2706,7 @@ void QWizard::setButtonLayout(const QList<WizardButton> &layout) { Q_D(QWizard); - for (int i = 0; i < layout.count(); ++i) { + for (int i = 0; i < layout.size(); ++i) { WizardButton button1 = layout.at(i); if (button1 == NoButton || button1 == Stretch) @@ -2891,7 +2891,7 @@ void QWizard::setDefaultProperty(const char *className, const char *property, const char *changedSignal) { Q_D(QWizard); - for (int i = d->defaultPropertyTable.count() - 1; i >= 0; --i) { + for (int i = d->defaultPropertyTable.size() - 1; i >= 0; --i) { if (qstrcmp(d->defaultPropertyTable.at(i).className, className) == 0) { d->defaultPropertyTable.remove(i); break; @@ -3071,7 +3071,7 @@ QSize QWizard::sizeHint() const void QWizard::back() { Q_D(QWizard); - int n = d->history.count() - 2; + int n = d->history.size() - 2; if (n < 0) return; d->switchToPage(d->history.at(n), QWizardPrivate::Backward); @@ -3670,7 +3670,7 @@ bool QWizardPage::isComplete() const return true; const QList<QWizardField> &wizardFields = d->wizard->d_func()->fields; - for (int i = wizardFields.count() - 1; i >= 0; --i) { + for (int i = wizardFields.size() - 1; i >= 0; --i) { const QWizardField &field = wizardFields.at(i); if (field.page == this && field.mandatory) { QVariant value = field.object->property(field.property); diff --git a/src/widgets/doc/snippets/code/doc_src_stylesheet.cpp b/src/widgets/doc/snippets/code/doc_src_stylesheet.cpp index 7fbcc493de..91851f8f07 100644 --- a/src/widgets/doc/snippets/code/doc_src_stylesheet.cpp +++ b/src/widgets/doc/snippets/code/doc_src_stylesheet.cpp @@ -51,7 +51,7 @@ qApp->setStyleSheet("ns--MyPushButton { background: yellow; }"); void CustomWidget::paintEvent(QPaintEvent *) { QStyleOption opt; - opt.init(this); + opt.initFrom(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); } diff --git a/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp b/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp index dbf776cf70..197c23f247 100644 --- a/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp +++ b/src/widgets/doc/snippets/code/src_gui_dialogs_qfiledialog.cpp @@ -110,5 +110,7 @@ QFileDialog::getOpenFileContent("Images (*.png *.xpm *.jpg)", fileContentReady) //! [16] QByteArray imageData; // obtained from e.g. QImage::save() -QFileDialog::saveFile("myimage.png", imageData); +QFileDialog::saveFileContent(imageData, "myimage.png"); // with filename hint +// OR +QFileDialog::saveFileContent(imageData); // no filename hint //! [16] diff --git a/src/widgets/doc/snippets/code/src_gui_widgets_qmenu.cpp b/src/widgets/doc/snippets/code/src_gui_widgets_qmenu.cpp index 70fb1fe62d..b0b0500fab 100644 --- a/src/widgets/doc/snippets/code/src_gui_widgets_qmenu.cpp +++ b/src/widgets/doc/snippets/code/src_gui_widgets_qmenu.cpp @@ -34,7 +34,7 @@ exec(e->globalPos()); //! [6] QMenu menu; QAction *at = actions[0]; // Assumes actions is not empty -for (QAction *a : qAsConst(actions)) +for (QAction *a : std::as_const(actions)) menu.addAction(a); menu.exec(pos, at); //! [6] diff --git a/src/widgets/doc/snippets/qlistview-dnd/model.cpp b/src/widgets/doc/snippets/qlistview-dnd/model.cpp index 045d1e81f9..be2189d1be 100644 --- a/src/widgets/doc/snippets/qlistview-dnd/model.cpp +++ b/src/widgets/doc/snippets/qlistview-dnd/model.cpp @@ -74,7 +74,7 @@ bool DragDropListModel::dropMimeData(const QMimeData *data, //! [6] insertRows(beginRow, rows, QModelIndex()); - for (const QString &text : qAsConst(newItems)) { + for (const QString &text : std::as_const(newItems)) { QModelIndex idx = index(beginRow, 0, QModelIndex()); setData(idx, text); beginRow++; diff --git a/src/widgets/doc/snippets/simplemodel-use/main.cpp b/src/widgets/doc/snippets/simplemodel-use/main.cpp index 62739b1f99..5a3d6ecce0 100644 --- a/src/widgets/doc/snippets/simplemodel-use/main.cpp +++ b/src/widgets/doc/snippets/simplemodel-use/main.cpp @@ -7,55 +7,61 @@ A simple example of how to access items from an existing model. */ -#include <QtGui> +#include <QApplication> +#include <QLabel> +#include <QVBoxLayout> +#include <QWidget> + +#include <QFileSystemModel> +#include <QPalette> + +#include <QDir> +#include <QModelIndex> /*! Create a default directory model and, using the index-based interface to the model and some QLabel widgets, populate the window's layout with the names of objects in the directory. - - Note that we only want to read the filenames in the highest level of the - directory, so we supply a default (invalid) QModelIndex to the model in - order to indicate that we want top-level items. */ int main(int argc, char *argv[]) { QApplication app(argc, argv); - QWidget *window = new QWidget; - QVBoxLayout *layout = new QVBoxLayout(window); - QLabel *title = new QLabel("Some items from the directory model", window); + QWidget window; + auto *layout = new QVBoxLayout(&window); + auto *title = new QLabel("Some items from the directory model", &window); title->setBackgroundRole(QPalette::Base); title->setMargin(8); layout->addWidget(title); //! [0] - QFileSystemModel *model = new QFileSystemModel; - connect(model, &QFileSystemModel::directoryLoaded, [model](const QString &directory) { - QModelIndex parentIndex = model->index(directory); - int numRows = model->rowCount(parentIndex); - }); - model->setRootPath(QDir::currentPath); -//! [0] + auto *model = new QFileSystemModel; + auto onDirectoryLoaded = [model, layout, &window](const QString &directory) { + QModelIndex parentIndex = model->index(directory); + const int numRows = model->rowCount(parentIndex); //! [1] - for (int row = 0; row < numRows; ++row) { - QModelIndex index = model->index(row, 0, parentIndex); + for (int row = 0; row < numRows; ++row) { + QModelIndex index = model->index(row, 0, parentIndex); //! [1] //! [2] - QString text = model->data(index, Qt::DisplayRole).toString(); - // Display the text in a widget. + QString text = model->data(index, Qt::DisplayRole).toString(); //! [2] - - QLabel *label = new QLabel(text, window); - layout->addWidget(label); + // Display the text in a widget. + auto *label = new QLabel(text, &window); + layout->addWidget(label); //! [3] - } + } //! [3] + }; + + QObject::connect(model, &QFileSystemModel::directoryLoaded, onDirectoryLoaded); + model->setRootPath(QDir::currentPath()); +//! [0] - window->setWindowTitle("A simple model example"); - window->show(); + window.setWindowTitle("A simple model example"); + window.show(); return app.exec(); } diff --git a/src/widgets/doc/snippets/updating-selections/window.cpp b/src/widgets/doc/snippets/updating-selections/window.cpp index b47e15e084..b965b81008 100644 --- a/src/widgets/doc/snippets/updating-selections/window.cpp +++ b/src/widgets/doc/snippets/updating-selections/window.cpp @@ -42,7 +42,7 @@ void MainWindow::updateSelection(const QItemSelection &selected, { QModelIndexList items = selected.indexes(); - for (const QModelIndex &index : qAsConst(items)) { + for (const QModelIndex &index : std::as_const(items)) { QString text = QString("(%1,%2)").arg(index.row()).arg(index.column()); model->setData(index, text); //! [0] //! [1] @@ -52,7 +52,7 @@ void MainWindow::updateSelection(const QItemSelection &selected, //! [2] items = deselected.indexes(); - for (const QModelIndex &index : qAsConst(items)) { + for (const QModelIndex &index : std::as_const(items)) { model->setData(index, QString()); } //! [2] diff --git a/src/widgets/doc/src/cmake-macros.qdoc b/src/widgets/doc/src/cmake-macros.qdoc index 4e947694f8..34bc254962 100644 --- a/src/widgets/doc/src/cmake-macros.qdoc +++ b/src/widgets/doc/src/cmake-macros.qdoc @@ -2,7 +2,7 @@ // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only /*! -\page qt_wrap_ui.html +\page qt-wrap-ui.html \ingroup cmake-macros-qtwidgets \title qt_wrap_ui diff --git a/src/widgets/doc/src/model-view-programming.qdoc b/src/widgets/doc/src/model-view-programming.qdoc index e0febae255..5c09fd0445 100644 --- a/src/widgets/doc/src/model-view-programming.qdoc +++ b/src/widgets/doc/src/model-view-programming.qdoc @@ -449,11 +449,13 @@ \snippet simplemodel-use/main.cpp 0 In this case, we start by setting up a default QFileSystemModel. We connect - it to a lambda, in which we will obtain a parent index using a specific + its signal \c directoryLoaded(QString) to a lambda, in which we will + obtain a parent index for the directory using a specific implementation of \l{QFileSystemModel::}{index()} provided by that model. - In the lambda, we count the number of rows in the model using the - \l{QFileSystemModel::}{rowCount()} function. Finally, we set the root path - of the QFileSystemModel so it starts loading data and triggers the lambda. + + In the lambda, we determine the number of rows in the model using the + \l{QFileSystemModel::}{rowCount()} function. + For simplicity, we are only interested in the items in the first column of the model. We examine each row in turn, obtaining a model index for @@ -474,6 +476,9 @@ \codeline \snippet simplemodel-use/main.cpp 3 + Finally, we set the root path of the QFileSystemModel so it starts + loading data and triggers the lambda. + The above example demonstrates the basic principles used to retrieve data from a model: diff --git a/src/widgets/doc/src/qtwidgets-index.qdoc b/src/widgets/doc/src/qtwidgets-index.qdoc index cbdd4b2a44..c0fa5cf3e0 100644 --- a/src/widgets/doc/src/qtwidgets-index.qdoc +++ b/src/widgets/doc/src/qtwidgets-index.qdoc @@ -115,6 +115,7 @@ interfaces \list \li \l{Qt Widgets Examples} \li \l{Layout Examples} + \li \l{Tools Examples} \endlist \section1 API Reference diff --git a/src/widgets/doc/src/widgets-and-layouts/focus.qdoc b/src/widgets/doc/src/widgets-and-layouts/focus.qdoc index 4214f025f1..6b4d119663 100644 --- a/src/widgets/doc/src/widgets-and-layouts/focus.qdoc +++ b/src/widgets/doc/src/widgets-and-layouts/focus.qdoc @@ -131,9 +131,7 @@ shortcuts for each of its pages, so the user can press e.g. \uicontrol Alt+P to step to the \underline{P}rinting page. It is easy to overdo this: there are only a few keys, and it's also important - to provide keyboard shortcuts for commands. \uicontrol Alt+P is also - used for Paste, Play, Print, and Print Here in the \l{Standard - Accelerator Keys} list, for example. + to provide keyboard shortcuts for commands. \section2 The User Rotates the Mouse Wheel diff --git a/src/widgets/effects/qgraphicseffect_p.h b/src/widgets/effects/qgraphicseffect_p.h index 4f9313e2b7..378258148c 100644 --- a/src/widgets/effects/qgraphicseffect_p.h +++ b/src/widgets/effects/qgraphicseffect_p.h @@ -121,6 +121,7 @@ public: QGraphicsEffect::ChangeFlags flags; if (source) { flags |= QGraphicsEffect::SourceDetached; + source->d_func()->effectBoundingRectChanged(); source->d_func()->invalidateCache(); source->d_func()->detach(); delete source; diff --git a/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp b/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp index 16286e47bf..db7401c024 100644 --- a/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp +++ b/src/widgets/graphicsview/qgraphicsanchorlayout_p.cpp @@ -459,7 +459,7 @@ void SequentialAnchorData::updateChildrenSizes() // "from" or "to", that _contains_ one of them. AnchorVertex *prev = from; - for (int i = 0; i < m_edges.count(); ++i) { + for (int i = 0; i < m_edges.size(); ++i) { AnchorData *e = m_edges.at(i); const bool edgeIsForward = (e->from == prev); @@ -496,7 +496,7 @@ void SequentialAnchorData::calculateSizeHints() AnchorVertex *prev = from; - for (int i = 0; i < m_edges.count(); ++i) { + for (int i = 0; i < m_edges.size(); ++i) { AnchorData *edge = m_edges.at(i); const bool edgeIsForward = (edge->from == prev); @@ -664,7 +664,7 @@ AnchorData *QGraphicsAnchorLayoutPrivate::addAnchorMaybeParallel(AnchorData *new parallel->isCenterAnchor = true; - for (int j = 0; j < constraints.count(); ++j) { + for (int j = 0; j < constraints.size(); ++j) { QSimplexConstraint *c = constraints[j]; if (c->variables.contains(child)) { childConstraints->append(c); @@ -710,9 +710,9 @@ static AnchorData *createSequence(Graph<AnchorVertex, AnchorData> *graph, Anchor AnchorVertex *prev = before; QList<AnchorData *> edges; - edges.reserve(vertices.count() + 1); + edges.reserve(vertices.size() + 1); - const int numVertices = vertices.count(); + const int numVertices = vertices.size(); edges.reserve(numVertices + 1); // Take from the graph, the edges that will be simplificated for (int i = 0; i < numVertices; ++i) { @@ -838,7 +838,7 @@ bool QGraphicsAnchorLayoutPrivate::replaceVertex(Qt::Orientation orientation, An Graph<AnchorVertex, AnchorData> &g = graph[orientation]; bool feasible = true; - for (int i = 0; i < edges.count(); ++i) { + for (int i = 0; i < edges.size(); ++i) { AnchorData *ad = edges[i]; AnchorVertex *otherV = replaceVertex_helper(ad, oldV, newV); @@ -886,7 +886,7 @@ bool QGraphicsAnchorLayoutPrivate::simplifyVertices(Qt::Orientation orientation) QList<AnchorVertex *> adjacents = g.adjacentVertices(v); int index = 0; - while (index < adjacents.count()) { + while (index < adjacents.size()) { AnchorVertex *next = adjacents.at(index); index++; @@ -906,7 +906,7 @@ bool QGraphicsAnchorLayoutPrivate::simplifyVertices(Qt::Orientation orientation) const QList<AnchorVertex *> &vAdjacents = g.adjacentVertices(v); const QList<AnchorVertex *> &nextAdjacents = g.adjacentVertices(next); - for (int i = 0; i < vAdjacents.count(); ++i) { + for (int i = 0; i < vAdjacents.size(); ++i) { AnchorVertex *adjacent = vAdjacents.at(i); if (adjacent != next) { AnchorData *ad = g.edgeData(v, adjacent); @@ -914,7 +914,7 @@ bool QGraphicsAnchorLayoutPrivate::simplifyVertices(Qt::Orientation orientation) } } - for (int i = 0; i < nextAdjacents.count(); ++i) { + for (int i = 0; i < nextAdjacents.size(); ++i) { AnchorVertex *adjacent = nextAdjacents.at(i); if (adjacent != v) { AnchorData *ad = g.edgeData(next, adjacent); @@ -1017,7 +1017,7 @@ bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(Qt::Orientation orient // // Identifies cases (a) and (b) - endOfSequence = isLayoutVertex || adjacents.count() != 2; + endOfSequence = isLayoutVertex || adjacents.size() != 2; if (!endOfSequence) { // This is a tricky part. We peek at the next vertex to find out whether @@ -1059,7 +1059,7 @@ bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(Qt::Orientation orient // // Add next non-visited vertices to the stack. // - for (int i = 0; i < adjacents.count(); ++i) { + for (int i = 0; i < adjacents.size(); ++i) { AnchorVertex *next = adjacents.at(i); if (visited.contains(next)) continue; @@ -1098,7 +1098,7 @@ bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(Qt::Orientation orient const AnchorData *lastAnchor = g.edgeData(candidates.constLast(), afterSequence); if (lastAnchor->isCenterAnchor) { afterSequence = candidates.constLast(); - candidates.remove(candidates.count() - 1); + candidates.remove(candidates.size() - 1); if (candidates.isEmpty()) continue; @@ -1153,7 +1153,7 @@ void QGraphicsAnchorLayoutPrivate::restoreSimplifiedAnchor(AnchorData *edge) } else if (edge->type == AnchorData::Sequential) { SequentialAnchorData *sequence = static_cast<SequentialAnchorData *>(edge); - for (int i = 0; i < sequence->m_edges.count(); ++i) { + for (int i = 0; i < sequence->m_edges.size(); ++i) { AnchorData *data = sequence->m_edges.at(i); restoreSimplifiedAnchor(data); } @@ -1188,7 +1188,7 @@ void QGraphicsAnchorLayoutPrivate::restoreSimplifiedConstraints(ParallelAnchorDa if (!parallel->isCenterAnchor) return; - for (int i = 0; i < parallel->m_firstConstraints.count(); ++i) { + for (int i = 0; i < parallel->m_firstConstraints.size(); ++i) { QSimplexConstraint *c = parallel->m_firstConstraints.at(i); qreal v = c->variables[parallel]; c->variables.remove(parallel); @@ -1199,7 +1199,7 @@ void QGraphicsAnchorLayoutPrivate::restoreSimplifiedConstraints(ParallelAnchorDa // addAnchorMaybeParallel(). const bool needsReverse = !parallel->secondForward(); - for (int i = 0; i < parallel->m_secondConstraints.count(); ++i) { + for (int i = 0; i < parallel->m_secondConstraints.size(); ++i) { QSimplexConstraint *c = parallel->m_secondConstraints.at(i); qreal v = c->variables[parallel]; if (needsReverse) @@ -1219,7 +1219,7 @@ void QGraphicsAnchorLayoutPrivate::restoreSimplifiedGraph(Qt::Orientation orient // Restore anchor simplification Graph<AnchorVertex, AnchorData> &g = graph[orientation]; QList<QPair<AnchorVertex *, AnchorVertex *>> connections = g.connections(); - for (int i = 0; i < connections.count(); ++i) { + for (int i = 0; i < connections.size(); ++i) { AnchorVertex *v1 = connections.at(i).first; AnchorVertex *v2 = connections.at(i).second; AnchorData *edge = g.edgeData(v1, v2); @@ -1255,14 +1255,14 @@ void QGraphicsAnchorLayoutPrivate::restoreVertices(Qt::Orientation orientation) // In the next step, we'll change the anchors vertices so that would not be possible anymore. QList<AnchorData *> ¶llelAnchors = anchorsFromSimplifiedVertices[orientation]; - for (int i = parallelAnchors.count() - 1; i >= 0; --i) { + for (int i = parallelAnchors.size() - 1; i >= 0; --i) { ParallelAnchorData *parallel = static_cast<ParallelAnchorData *>(parallelAnchors.at(i)); restoreSimplifiedConstraints(parallel); } // Then, we will restore the vertices in the inverse order of creation, this way we ensure that // the vertex being restored was not wrapped by another simplification. - for (int i = toRestore.count() - 1; i >= 0; --i) { + for (int i = toRestore.size() - 1; i >= 0; --i) { AnchorVertexPair *pair = toRestore.at(i); QList<AnchorVertex *> adjacents = g.adjacentVertices(pair); @@ -1273,7 +1273,7 @@ void QGraphicsAnchorLayoutPrivate::restoreVertices(Qt::Orientation orientation) g.createEdge(first, second, pair->m_removedAnchor); // Restore the anchors for the first child vertex - for (int j = 0; j < pair->m_firstAnchors.count(); ++j) { + for (int j = 0; j < pair->m_firstAnchors.size(); ++j) { AnchorData *ad = pair->m_firstAnchors.at(j); Q_ASSERT(ad->from == pair || ad->to == pair); @@ -1282,7 +1282,7 @@ void QGraphicsAnchorLayoutPrivate::restoreVertices(Qt::Orientation orientation) } // Restore the anchors for the second child vertex - for (int j = 0; j < pair->m_secondAnchors.count(); ++j) { + for (int j = 0; j < pair->m_secondAnchors.size(); ++j) { AnchorData *ad = pair->m_secondAnchors.at(j); Q_ASSERT(ad->from == pair || ad->to == pair); @@ -1290,7 +1290,7 @@ void QGraphicsAnchorLayoutPrivate::restoreVertices(Qt::Orientation orientation) g.createEdge(ad->from, ad->to, ad); } - for (int j = 0; j < adjacents.count(); ++j) { + for (int j = 0; j < adjacents.size(); ++j) { g.takeEdge(pair, adjacents.at(j)); } @@ -1500,7 +1500,7 @@ void QGraphicsAnchorLayoutPrivate::removeCenterAnchors( AnchorData *oldData = g.edgeData(first, center); // Remove center constraint - for (int i = itemCenterConstraints[orientation].count() - 1; i >= 0; --i) { + for (int i = itemCenterConstraints[orientation].size() - 1; i >= 0; --i) { if (itemCenterConstraints[orientation].at(i)->variables.contains(oldData)) { delete itemCenterConstraints[orientation].takeAt(i); break; @@ -1521,7 +1521,7 @@ void QGraphicsAnchorLayoutPrivate::removeCenterAnchors( // this is only called from removeAnchors() // first, remove all non-internal anchors QList<AnchorVertex*> adjacents = g.adjacentVertices(center); - for (int i = 0; i < adjacents.count(); ++i) { + for (int i = 0; i < adjacents.size(); ++i) { AnchorVertex *v = adjacents.at(i); if (v->m_item != item) { removeAnchor_helper(center, internalVertex(v->m_item, v->m_edge)); @@ -2014,7 +2014,7 @@ void QGraphicsAnchorLayoutPrivate::calculateGraphs() QList<AnchorData *> getVariables(const QList<QSimplexConstraint *> &constraints) { QSet<AnchorData *> variableSet; - for (int i = 0; i < constraints.count(); ++i) { + for (int i = 0; i < constraints.size(); ++i) { const QSimplexConstraint *c = constraints.at(i); for (auto it = c->variables.cbegin(), end = c->variables.cend(); it != end; ++it) variableSet.insert(static_cast<AnchorData *>(it.key())); @@ -2129,7 +2129,7 @@ void QGraphicsAnchorLayoutPrivate::calculateGraphs(Qt::Orientation orientation) */ static void shiftConstraints(const QList<QSimplexConstraint *> &constraints, qreal amount) { - for (int i = 0; i < constraints.count(); ++i) { + for (int i = 0; i < constraints.size(); ++i) { QSimplexConstraint *c = constraints.at(i); const qreal multiplier = std::accumulate(c->variables.cbegin(), c->variables.cend(), qreal(0)); c->constant += multiplier * amount; @@ -2187,8 +2187,8 @@ bool QGraphicsAnchorLayoutPrivate::calculateTrunk(Qt::Orientation orientation, c } else { // No Simplex is necessary because the path was simplified all the way to a single // anchor. - Q_ASSERT(path.positives.count() == 1); - Q_ASSERT(path.negatives.count() == 0); + Q_ASSERT(path.positives.size() == 1); + Q_ASSERT(path.negatives.size() == 0); AnchorData *ad = *path.positives.cbegin(); ad->sizeAtMinimum = ad->minSize; @@ -2219,7 +2219,7 @@ bool QGraphicsAnchorLayoutPrivate::calculateNonTrunk(const QList<QSimplexConstra if (feasible) { // Propagate size at preferred to other sizes. Semi-floats always will be // in their sizeAtPreferred. - for (int j = 0; j < variables.count(); ++j) { + for (int j = 0; j < variables.size(); ++j) { AnchorData *ad = variables.at(j); Q_ASSERT(ad); ad->sizeAtMinimum = ad->sizeAtPreferred; @@ -2243,7 +2243,7 @@ void QGraphicsAnchorLayoutPrivate::refreshAllSizeHints(Qt::Orientation orientati QList<QPair<AnchorVertex *, AnchorVertex *>> vertices = g.connections(); QLayoutStyleInfo styleInf = styleInfo(); - for (int i = 0; i < vertices.count(); ++i) { + for (int i = 0; i < vertices.size(); ++i) { AnchorData *data = g.edgeData(vertices.at(i).first, vertices.at(i).second); data->refreshSizeHints(&styleInf); } @@ -2335,7 +2335,7 @@ void QGraphicsAnchorLayoutPrivate::updateAnchorSizes(Qt::Orientation orientation Graph<AnchorVertex, AnchorData> &g = graph[orientation]; const QList<QPair<AnchorVertex *, AnchorVertex *>> &vertices = g.connections(); - for (int i = 0; i < vertices.count(); ++i) { + for (int i = 0; i < vertices.size(); ++i) { AnchorData *ad = g.edgeData(vertices.at(i).first, vertices.at(i).second); ad->updateChildrenSizes(); } @@ -2478,7 +2478,7 @@ QGraphicsAnchorLayoutPrivate::getGraphParts(Qt::Orientation orientation) // Check if this constraint have some overlap with current // trunk variables... - for (QSimplexVariable *ad : qAsConst(trunkVariables)) { + for (QSimplexVariable *ad : std::as_const(trunkVariables)) { if (c->variables.contains(ad)) { match = true; break; @@ -2527,7 +2527,7 @@ void QGraphicsAnchorLayoutPrivate::identifyFloatItems(const QSet<AnchorData *> & identifyNonFloatItems_helper(ad, &nonFloating); QSet<QGraphicsLayoutItem *> floatItems; - for (QGraphicsLayoutItem *item : qAsConst(items)) { + for (QGraphicsLayoutItem *item : std::as_const(items)) { if (!nonFloating.contains(item)) floatItems.insert(item); } @@ -2586,7 +2586,7 @@ void QGraphicsAnchorLayoutPrivate::setItemsGeometries(const QRectF &geom) top += geom.top(); right = geom.right() - right; - for (QGraphicsLayoutItem *item : qAsConst(items)) { + for (QGraphicsLayoutItem *item : std::as_const(items)) { QRectF newGeom; QSizeF itemPreferredSize = item->effectiveSizeHint(Qt::PreferredSize); if (m_floatItems[Qt::Horizontal].contains(item)) { @@ -2657,7 +2657,7 @@ void QGraphicsAnchorLayoutPrivate::calculateVertexPositions(Qt::Orientation orie interpolateEdge(pair.first, edge); QList<AnchorVertex *> adjacents = graph[orientation].adjacentVertices(pair.second); - for (int i = 0; i < adjacents.count(); ++i) { + for (int i = 0; i < adjacents.size(); ++i) { if (!visited.contains(adjacents.at(i))) queue.enqueue(qMakePair(pair.second, adjacents.at(i))); } @@ -2741,7 +2741,7 @@ bool QGraphicsAnchorLayoutPrivate::solveMinMax(const QList<QSimplexConstraint *> for (iter = path.negatives.constBegin(); iter != path.negatives.constEnd(); ++iter) objective.variables.insert(*iter, -1.0); - const qreal objectiveOffset = (path.positives.count() - path.negatives.count()) * g_offset; + const qreal objectiveOffset = (path.positives.size() - path.negatives.size()) * g_offset; simplex.setObjective(&objective); // Calculate minimum values diff --git a/src/widgets/graphicsview/qgraphicsgridlayoutengine_p.h b/src/widgets/graphicsview/qgraphicsgridlayoutengine_p.h index 06a2de1ea8..f3b2ec3731 100644 --- a/src/widgets/graphicsview/qgraphicsgridlayoutengine_p.h +++ b/src/widgets/graphicsview/qgraphicsgridlayoutengine_p.h @@ -83,7 +83,7 @@ public: int indexOf(QGraphicsLayoutItem *item) const { - for (int i = 0; i < q_items.count(); ++i) { + for (int i = 0; i < q_items.size(); ++i) { if (item == static_cast<QGraphicsGridLayoutEngineItem*>(q_items.at(i))->layoutItem()) return i; } diff --git a/src/widgets/graphicsview/qgraphicsitem.cpp b/src/widgets/graphicsview/qgraphicsitem.cpp index 9008b54d84..f622670aff 100644 --- a/src/widgets/graphicsview/qgraphicsitem.cpp +++ b/src/widgets/graphicsview/qgraphicsitem.cpp @@ -1036,7 +1036,7 @@ void QGraphicsItemPrivate::setIsMemberOfGroup(bool enabled) Q_Q(QGraphicsItem); isMemberOfGroup = enabled; if (!qgraphicsitem_cast<QGraphicsItemGroup *>(q)) { - for (QGraphicsItem *child : qAsConst(children)) + for (QGraphicsItem *child : std::as_const(children)) child->d_func()->setIsMemberOfGroup(enabled); } } @@ -2175,7 +2175,7 @@ bool QGraphicsItem::isBlockedByModalPanel(QGraphicsItem **blockingPanel) const if (!scene_d->popupWidgets.isEmpty() && scene_d->popupWidgets.first() == this) return false; - for (int i = 0; i < scene_d->modalPanels.count(); ++i) { + for (int i = 0; i < scene_d->modalPanels.size(); ++i) { QGraphicsItem *modalPanel = scene_d->modalPanels.at(i); if (modalPanel->panelModality() == QGraphicsItem::SceneModal) { // Scene modal panels block all non-descendents. @@ -2458,7 +2458,7 @@ void QGraphicsItemPrivate::setVisibleHelper(bool newVisible, bool explicitly, const bool updateChildren = update && !((flags & QGraphicsItem::ItemClipsChildrenToShape || flags & QGraphicsItem::ItemContainsChildrenInShape) && !(flags & QGraphicsItem::ItemHasNoContents)); - for (QGraphicsItem *child : qAsConst(children)) { + for (QGraphicsItem *child : std::as_const(children)) { if (!newVisible || !child->d_ptr->explicitlyHidden) child->d_ptr->setVisibleHelper(newVisible, false, updateChildren, hiddenByPanel); } @@ -2650,7 +2650,7 @@ void QGraphicsItemPrivate::setEnabledHelper(bool newEnabled, bool explicitly, bo if (update) q_ptr->update(); - for (QGraphicsItem *child : qAsConst(children)) { + for (QGraphicsItem *child : std::as_const(children)) { if (!newEnabled || !child->d_ptr->explicitlyDisabled) child->d_ptr->setEnabledHelper(newEnabled, /* explicitly = */ false); } @@ -3917,7 +3917,7 @@ void QGraphicsItem::ensureVisible(const QRectF &rect, int xmargin, int ymargin) sceneRect = sceneTransform().mapRect(rect); else sceneRect = sceneBoundingRect(); - for (QGraphicsView *view : qAsConst(d_ptr->scene->d_func()->views)) + for (QGraphicsView *view : std::as_const(d_ptr->scene->d_func()->views)) view->ensureVisible(sceneRect, xmargin, ymargin); } } @@ -4627,7 +4627,7 @@ inline void QGraphicsItemPrivate::sendScenePosChange() if (flags & QGraphicsItem::ItemSendsScenePositionChanges) q->itemChange(QGraphicsItem::ItemScenePositionHasChanged, q->scenePos()); if (scenePosDescendants) { - for (QGraphicsItem *item : qAsConst(scene->d_func()->scenePosItems)) { + for (QGraphicsItem *item : std::as_const(scene->d_func()->scenePosItems)) { if (q->isAncestorOf(item)) item->itemChange(QGraphicsItem::ItemScenePositionHasChanged, item->scenePos()); } @@ -7083,7 +7083,7 @@ void QGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) selectedItems = d_ptr->scene->selectedItems(); initialPositions = d_ptr->scene->d_func()->movingItemsInitialPositions; if (initialPositions.isEmpty()) { - for (QGraphicsItem *item : qAsConst(selectedItems)) + for (QGraphicsItem *item : std::as_const(selectedItems)) initialPositions[item] = item->pos(); initialPositions[this] = pos(); } @@ -7192,7 +7192,7 @@ void QGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) // temporarily removing this item from the selection list. if (d_ptr->selected) { scene->d_func()->selectedItems.remove(this); - for (QGraphicsItem *item : qAsConst(scene->d_func()->selectedItems)) { + for (QGraphicsItem *item : std::as_const(scene->d_func()->selectedItems)) { if (item->isSelected()) { selectionChanged = true; break; @@ -7665,13 +7665,13 @@ void QGraphicsItemPrivate::children_append(QDeclarativeListProperty<QGraphicsObj int QGraphicsItemPrivate::children_count(QDeclarativeListProperty<QGraphicsObject> *list) { QGraphicsItemPrivate *d = QGraphicsItemPrivate::get(static_cast<QGraphicsObject *>(list->object)); - return d->children.count(); + return d->children.size(); } QGraphicsObject *QGraphicsItemPrivate::children_at(QDeclarativeListProperty<QGraphicsObject> *list, int index) { QGraphicsItemPrivate *d = QGraphicsItemPrivate::get(static_cast<QGraphicsObject *>(list->object)); - if (index >= 0 && index < d->children.count()) + if (index >= 0 && index < d->children.size()) return d->children.at(index)->toGraphicsObject(); else return nullptr; @@ -7680,7 +7680,7 @@ QGraphicsObject *QGraphicsItemPrivate::children_at(QDeclarativeListProperty<QGra void QGraphicsItemPrivate::children_clear(QDeclarativeListProperty<QGraphicsObject> *list) { QGraphicsItemPrivate *d = QGraphicsItemPrivate::get(static_cast<QGraphicsObject *>(list->object)); - int childCount = d->children.count(); + int childCount = d->children.size(); if (d->sendParentChangeNotification) { for (int index = 0; index < childCount; index++) d->children.at(0)->setParentItem(nullptr); @@ -10749,7 +10749,7 @@ void QGraphicsSimpleTextItem::paint(QPainter *painter, const QStyleOptionGraphic } else { QTextLayout::FormatRange range; range.start = 0; - range.length = layout.text().length(); + range.length = layout.text().size(); range.format.setTextOutline(d->pen); layout.setFormats(QList<QTextLayout::FormatRange>(1, range)); } diff --git a/src/widgets/graphicsview/qgraphicsproxywidget.cpp b/src/widgets/graphicsview/qgraphicsproxywidget.cpp index d00851c1aa..60d62c084b 100644 --- a/src/widgets/graphicsview/qgraphicsproxywidget.cpp +++ b/src/widgets/graphicsview/qgraphicsproxywidget.cpp @@ -461,7 +461,7 @@ void QGraphicsProxyWidgetPrivate::embedSubWindow(QWidget *subWin) */ void QGraphicsProxyWidgetPrivate::unembedSubWindow(QWidget *subWin) { - for (QGraphicsItem *child : qAsConst(children)) { + for (QGraphicsItem *child : std::as_const(children)) { if (child->isWidget()) { if (QGraphicsProxyWidget *proxy = qobject_cast<QGraphicsProxyWidget *>(static_cast<QGraphicsWidget *>(child))) { if (proxy->widget() == subWin) { diff --git a/src/widgets/graphicsview/qgraphicsscene.cpp b/src/widgets/graphicsview/qgraphicsscene.cpp index f65082ad55..dbe6ed9b02 100644 --- a/src/widgets/graphicsview/qgraphicsscene.cpp +++ b/src/widgets/graphicsview/qgraphicsscene.cpp @@ -330,7 +330,7 @@ void QGraphicsScenePrivate::_q_emitUpdated() // needs to happen in order to keep compatibility with the behavior from // Qt 4.4 and backward. if (isSignalConnected(changedSignalIndex)) { - for (auto view : qAsConst(views)) { + for (auto view : std::as_const(views)) { if (!view->d_func()->connectedToScene) { view->d_func()->connectedToScene = true; q->connect(q, SIGNAL(changed(QList<QRectF>)), @@ -342,10 +342,10 @@ void QGraphicsScenePrivate::_q_emitUpdated() updateAll = false; return; } - for (auto view : qAsConst(views)) + for (auto view : std::as_const(views)) view->d_func()->processPendingUpdates(); // It's important that we update all views before we dispatch, hence two for-loops. - for (auto view : qAsConst(views)) + for (auto view : std::as_const(views)) view->d_func()->dispatchPendingUpdateRequests(); return; } @@ -411,7 +411,7 @@ void QGraphicsScenePrivate::_q_polishItems() const QVariant booleanTrueVariant(true); QGraphicsItem *item = nullptr; QGraphicsItemPrivate *itemd = nullptr; - const int oldUnpolishedCount = unpolishedItems.count(); + const int oldUnpolishedCount = unpolishedItems.size(); for (int i = 0; i < oldUnpolishedCount; ++i) { item = unpolishedItems.at(i); @@ -429,7 +429,7 @@ void QGraphicsScenePrivate::_q_polishItems() } } - if (unpolishedItems.count() == oldUnpolishedCount) { + if (unpolishedItems.size() == oldUnpolishedCount) { // No new items were added to the vector. unpolishedItems.clear(); } else { @@ -448,7 +448,7 @@ void QGraphicsScenePrivate::_q_processDirtyItems() Q_ASSERT(calledEmitUpdated); // No need for further processing (except resetting the dirty states). // The growingItemsBoundingRect is updated in _q_emitUpdated. - for (auto topLevelItem : qAsConst(topLevelItems)) + for (auto topLevelItem : std::as_const(topLevelItems)) resetDirtyItem(topLevelItem, /*recursive=*/true); return; } @@ -457,7 +457,7 @@ void QGraphicsScenePrivate::_q_processDirtyItems() const QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect; // Process items recursively. - for (auto topLevelItem : qAsConst(topLevelItems)) + for (auto topLevelItem : std::as_const(topLevelItems)) processDirtyItemsRecursive(topLevelItem); dirtyGrowingItemsBoundingRect = false; @@ -467,7 +467,7 @@ void QGraphicsScenePrivate::_q_processDirtyItems() if (wasPendingSceneUpdate) return; - for (auto view : qAsConst(views)) + for (auto view : std::as_const(views)) view->d_func()->processPendingUpdates(); if (calledEmitUpdated) { @@ -478,7 +478,7 @@ void QGraphicsScenePrivate::_q_processDirtyItems() } // Immediately dispatch all pending update requests on the views. - for (auto view : qAsConst(views)) + for (auto view : std::as_const(views)) view->d_func()->dispatchPendingUpdateRequests(); } @@ -521,7 +521,7 @@ void QGraphicsScenePrivate::unregisterScenePosItem(QGraphicsItem *item) */ void QGraphicsScenePrivate::_q_updateScenePosDescendants() { - for (QGraphicsItem *item : qAsConst(scenePosItems)) { + for (QGraphicsItem *item : std::as_const(scenePosItems)) { QGraphicsItem *p = item->d_ptr->parent; while (p) { p->d_ptr->scenePosDescendants = 1; @@ -574,7 +574,7 @@ void QGraphicsScenePrivate::removeItemHelper(QGraphicsItem *item) //attributes (e.g. sceneTransform). if (!item->d_ptr->inDestructor) { // Remove all children recursively - for (auto child : qAsConst(item->d_ptr->children)) + for (auto child : std::as_const(item->d_ptr->children)) q->removeItem(child); } @@ -1080,7 +1080,7 @@ void QGraphicsScenePrivate::clearKeyboardGrabber() void QGraphicsScenePrivate::enableMouseTrackingOnViews() { - for (QGraphicsView *view : qAsConst(views)) + for (QGraphicsView *view : std::as_const(views)) view->viewport()->setMouseTracking(true); } @@ -1343,7 +1343,7 @@ void QGraphicsScenePrivate::mousePressEventHandler(QGraphicsSceneMouseEvent *mou // Set focus on the topmost enabled item that can take focus. bool setFocus = false; - for (QGraphicsItem *item : qAsConst(cachedItemsUnderMouse)) { + for (QGraphicsItem *item : std::as_const(cachedItemsUnderMouse)) { if (item->isBlockedByModalPanel() || (item->d_ptr->flags & QGraphicsItem::ItemStopsFocusHandling)) { // Make sure we don't clear focus. @@ -1366,7 +1366,7 @@ void QGraphicsScenePrivate::mousePressEventHandler(QGraphicsSceneMouseEvent *mou // Check for scene modality. bool sceneModality = false; - for (auto modalPanel : qAsConst(modalPanels)) { + for (auto modalPanel : std::as_const(modalPanels)) { if (modalPanel->panelModality() == QGraphicsItem::SceneModal) { sceneModality = true; break; @@ -1385,7 +1385,7 @@ void QGraphicsScenePrivate::mousePressEventHandler(QGraphicsSceneMouseEvent *mou // candidates one at a time, until the event is accepted. It's accepted by // default, so the receiver has to explicitly ignore it for it to pass // through. - for (QGraphicsItem *item : qAsConst(cachedItemsUnderMouse)) { + for (QGraphicsItem *item : std::as_const(cachedItemsUnderMouse)) { if (!(item->acceptedMouseButtons() & mouseEvent->button())) { // Skip items that don't accept the event's mouse button. continue; @@ -1661,7 +1661,7 @@ QGraphicsScene::~QGraphicsScene() // Remove this scene from all associated views. // Note: d->views is modified by QGraphicsView::setScene, so must make a copy const auto views = d->views; - for (auto view : qAsConst(views)) + for (auto view : std::as_const(views)) view->setScene(nullptr); } @@ -1780,8 +1780,8 @@ void QGraphicsScene::render(QPainter *painter, const QRectF &target, const QRect // in reverse order). QList<QGraphicsItem *> itemList = items(sourceRect, Qt::IntersectsItemBoundingRect); QGraphicsItem **itemArray = new QGraphicsItem *[itemList.size()]; - const int numItems = itemList.size(); - for (int i = 0; i < numItems; ++i) + const qsizetype numItems = itemList.size(); + for (qsizetype i = 0; i < numItems; ++i) itemArray[numItems - i - 1] = itemList.at(i); itemList.clear(); @@ -1798,7 +1798,7 @@ void QGraphicsScene::render(QPainter *painter, const QRectF &target, const QRect // Generate the style options QStyleOptionGraphicsItem *styleOptionArray = new QStyleOptionGraphicsItem[numItems]; - for (int i = 0; i < numItems; ++i) + for (qsizetype i = 0; i < numItems; ++i) itemArray[i]->d_ptr->initStyleOption(&styleOptionArray[i], painterTransform, targetRect.toRect()); // Render the scene. @@ -2132,7 +2132,7 @@ QList<QGraphicsItem *> QGraphicsScene::selectedItems() const // Optimization: Lazily removes items that are not selected. QGraphicsScene *that = const_cast<QGraphicsScene *>(this); QSet<QGraphicsItem *> actuallySelectedSet; - for (QGraphicsItem *item : qAsConst(that->d_func()->selectedItems)) { + for (QGraphicsItem *item : std::as_const(that->d_func()->selectedItems)) { if (item->isSelected()) actuallySelectedSet << item; } @@ -2222,7 +2222,7 @@ void QGraphicsScene::setSelectionArea(const QPainterPath &path, switch (selectionOperation) { case Qt::ReplaceSelection: // Deselect all items outside path. - for (QGraphicsItem *item : qAsConst(unselectItems)) { + for (QGraphicsItem *item : std::as_const(unselectItems)) { item->setSelected(false); changed = true; } @@ -2516,7 +2516,7 @@ void QGraphicsScene::addItem(QGraphicsItem *item) // Add all children recursively item->d_ptr->ensureSortedChildren(); - for (auto child : qAsConst(item->d_ptr->children)) + for (auto child : std::as_const(item->d_ptr->children)) addItem(child); // Resolve font and palette. @@ -3019,7 +3019,7 @@ void QGraphicsScene::setBackgroundBrush(const QBrush &brush) { Q_D(QGraphicsScene); d->backgroundBrush = brush; - for (QGraphicsView *view : qAsConst(d->views)) { + for (QGraphicsView *view : std::as_const(d->views)) { view->resetCachedContent(); view->viewport()->update(); } @@ -3108,13 +3108,13 @@ void QGraphicsScene::update(const QRectF &rect) d->updatedRects.clear(); if (directUpdates) { // Update all views. - for (auto view : qAsConst(d->views)) + for (auto view : std::as_const(d->views)) view->d_func()->fullUpdatePending = true; } } else { if (directUpdates) { // Update all views. - for (auto view : qAsConst(d->views)) { + for (auto view : std::as_const(d->views)) { if (view->isTransformed()) view->d_func()->updateRectF(view->viewportTransform().mapRect(rect)); else @@ -3775,7 +3775,7 @@ bool QGraphicsScenePrivate::dispatchHoverEvent(QGraphicsSceneHoverEvent *hoverEv } QGraphicsItem *item = nullptr; - for (auto tmp : qAsConst(cachedItemsUnderMouse)) { + for (auto tmp : std::as_const(cachedItemsUnderMouse)) { if (itemAcceptsHoverEvents_helper(tmp)) { item = tmp; break; @@ -4398,7 +4398,7 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte QRegion pixmapExposed; QRectF exposedRect; if (!itemCache->allExposed) { - for (const auto &rect : qAsConst(itemCache->exposed)) { + for (const auto &rect : std::as_const(itemCache->exposed)) { exposedRect |= rect; pixmapExposed += itemToPixmap.mapRect(rect).toAlignedRect(); } @@ -4558,7 +4558,7 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte // Map the item's logical expose to pixmap coordinates. QRegion pixmapExposed = scrollExposure; if (!itemCache->allExposed) { - for (const auto &rect : qAsConst(itemCache->exposed)) + for (const auto &rect : std::as_const(itemCache->exposed)) pixmapExposed += itemToPixmap.mapRect(rect).toRect().adjusted(-1, -1, 1, 1); } @@ -4567,10 +4567,10 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte if (itemCache->allExposed) { br = item->boundingRect(); } else { - for (const auto &rect : qAsConst(itemCache->exposed)) + for (const auto &rect : std::as_const(itemCache->exposed)) br |= rect; QTransform pixmapToItem = itemToPixmap.inverted(); - for (const QRect &r : qAsConst(scrollExposure)) + for (const QRect &r : std::as_const(scrollExposure)) br |= pixmapToItem.mapRect(r); } styleOptionTmp = *option; @@ -4977,7 +4977,7 @@ void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, b return; } - for (auto view : qAsConst(views)) { + for (auto view : std::as_const(views)) { QGraphicsViewPrivate *viewPrivate = view->d_func(); QRect rect = item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport); rect.translate(viewPrivate->dirtyScrollOffset); @@ -5133,7 +5133,7 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool QRectF dirtyRect; bool uninitializedDirtyRect = true; - for (auto view : qAsConst(views)) { + for (auto view : std::as_const(views)) { QGraphicsViewPrivate *viewPrivate = view->d_func(); QRect &paintedViewBoundingRect = item->d_ptr->paintedViewBoundingRects[viewPrivate->viewport]; if (viewPrivate->fullUpdatePending @@ -5191,7 +5191,7 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool const bool bypassUpdateClip = !itemHasContents && wasDirtyParentViewBoundingRects; if (itemClipsChildrenToShape && !bypassUpdateClip) { // Make sure child updates are clipped to the item's bounding rect. - for (auto view : qAsConst(views)) + for (auto view : std::as_const(views)) view->d_func()->setUpdateClip(item); } if (!dirtyAncestorContainsChildren) { @@ -5201,7 +5201,7 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool const bool allChildrenDirty = item->d_ptr->allChildrenDirty; const bool parentIgnoresVisible = item->d_ptr->ignoreVisible; const bool parentIgnoresOpacity = item->d_ptr->ignoreOpacity; - for (auto child : qAsConst(item->d_ptr->children)) { + for (auto child : std::as_const(item->d_ptr->children)) { if (wasDirtyParentSceneTransform) child->d_ptr->dirtySceneTransform = 1; if (wasDirtyParentViewBoundingRects) @@ -5221,7 +5221,7 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool if (itemClipsChildrenToShape) { // Reset updateClip. - for (auto view : qAsConst(views)) + for (auto view : std::as_const(views)) view->d_func()->setUpdateClip(nullptr); } } else if (wasDirtyParentSceneTransform) { @@ -5302,7 +5302,7 @@ void QGraphicsScene::drawItems(QPainter *painter, d->rectAdjust = oldRectAdjust; // Reset discovery bits. - for (auto topLevelItem : qAsConst(topLevelItems)) + for (auto topLevelItem : std::as_const(topLevelItems)) topLevelItem->d_ptr->itemDiscovered = 0; painter->setWorldTransform(viewTransform); @@ -5821,7 +5821,7 @@ int QGraphicsScenePrivate::findClosestTouchPointId(const QPointF &scenePos) { int closestTouchPointId = -1; qreal closestDistance = qreal(0.); - for (const QEventPoint &touchPoint : qAsConst(sceneCurrentTouchPoints)) { + for (const QEventPoint &touchPoint : std::as_const(sceneCurrentTouchPoints)) { qreal distance = QLineF(scenePos, touchPoint.scenePosition()).length(); if (closestTouchPointId == -1|| distance < closestDistance) { closestTouchPointId = touchPoint.id(); @@ -5971,7 +5971,7 @@ bool QGraphicsScenePrivate::sendTouchBeginEvent(QGraphicsItem *origin, QTouchEve // Set focus on the topmost enabled item that can take focus. bool setFocus = false; - for (QGraphicsItem *item : qAsConst(cachedItemsUnderMouse)) { + for (QGraphicsItem *item : std::as_const(cachedItemsUnderMouse)) { if (item->isEnabled() && ((item->flags() & QGraphicsItem::ItemIsFocusable) && item->d_ptr->mouseSetsFocus)) { if (!item->isWidget() || ((QGraphicsWidget *)item)->focusPolicy() & Qt::ClickFocus) { setFocus = true; @@ -5998,7 +5998,7 @@ bool QGraphicsScenePrivate::sendTouchBeginEvent(QGraphicsItem *origin, QTouchEve bool res = false; bool eventAccepted = touchEvent->isAccepted(); - for (QGraphicsItem *item : qAsConst(cachedItemsUnderMouse)) { + for (QGraphicsItem *item : std::as_const(cachedItemsUnderMouse)) { // first, try to deliver the touch event updateTouchPointsForItem(item, touchEvent); bool acceptTouchEvents = item->acceptTouchEvents(); @@ -6030,13 +6030,13 @@ bool QGraphicsScenePrivate::sendTouchBeginEvent(QGraphicsItem *origin, QTouchEve void QGraphicsScenePrivate::enableTouchEventsOnViews() { - for (QGraphicsView *view : qAsConst(views)) + for (QGraphicsView *view : std::as_const(views)) view->viewport()->setAttribute(Qt::WA_AcceptTouchEvents, true); } void QGraphicsScenePrivate::updateInputMethodSensitivityInViews() { - for (auto view : qAsConst(views)) + for (auto view : std::as_const(views)) view->d_func()->updateInputMethodSensitivity(); } @@ -6402,7 +6402,7 @@ void QGraphicsScenePrivate::gestureEventHandler(QGestureEvent *event) } } - for (QGesture *g : qAsConst(startedGestures)) { + for (QGesture *g : std::as_const(startedGestures)) { if (g->gestureCancelPolicy() == QGesture::CancelAllInContext) { DEBUG() << "lets try to cancel some"; // find gestures in context in Qt::GestureStarted or Qt::GestureUpdated state and cancel them @@ -6515,7 +6515,7 @@ void QGraphicsScenePrivate::grabGesture(QGraphicsItem *, Qt::GestureType gesture { (void)QGestureManager::instance(); // create a gesture manager if (!grabbedGestures[gesture]++) { - for (QGraphicsView *view : qAsConst(views)) + for (QGraphicsView *view : std::as_const(views)) view->viewport()->grabGesture(gesture); } } @@ -6527,7 +6527,7 @@ void QGraphicsScenePrivate::ungrabGesture(QGraphicsItem *item, Qt::GestureType g QGraphicsObject *obj = static_cast<QGraphicsObject *>(item); QGestureManager::instance()->cleanupCachedGestures(obj, gesture); if (!--grabbedGestures[gesture]) { - for (QGraphicsView *view : qAsConst(views)) + for (QGraphicsView *view : std::as_const(views)) view->viewport()->ungrabGesture(gesture); } } diff --git a/src/widgets/graphicsview/qgraphicsscene_bsp.cpp b/src/widgets/graphicsview/qgraphicsscene_bsp.cpp index 7ee7f9b382..1ba6fe787a 100644 --- a/src/widgets/graphicsview/qgraphicsscene_bsp.cpp +++ b/src/widgets/graphicsview/qgraphicsscene_bsp.cpp @@ -80,7 +80,7 @@ QList<QGraphicsItem *> QGraphicsSceneBspTree::items(const QRectF &rect, bool onl } }, rect); // Reset discovery bits. - for (const auto &foundItem : qAsConst(foundItems)) + for (const auto &foundItem : std::as_const(foundItems)) foundItem->d_ptr->itemDiscovered = 0; return foundItems; } diff --git a/src/widgets/graphicsview/qgraphicsview.cpp b/src/widgets/graphicsview/qgraphicsview.cpp index 7bbe5d1608..2e3ea7aa31 100644 --- a/src/widgets/graphicsview/qgraphicsview.cpp +++ b/src/widgets/graphicsview/qgraphicsview.cpp @@ -666,7 +666,7 @@ void QGraphicsViewPrivate::mouseMoveEventHandler(QMouseEvent *event) mouseEvent.widget()); } // Find the topmost item under the mouse with a cursor. - for (QGraphicsItem *item : qAsConst(scene->d_func()->cachedItemsUnderMouse)) { + for (QGraphicsItem *item : std::as_const(scene->d_func()->cachedItemsUnderMouse)) { if (item->isEnabled() && item->hasCursor()) { _q_setViewportCursor(item->cursor()); return; @@ -2413,7 +2413,7 @@ QPolygonF QGraphicsView::mapToScene(const QRect &rect) const QPolygonF QGraphicsView::mapToScene(const QPolygon &polygon) const { QPolygonF poly; - poly.reserve(polygon.count()); + poly.reserve(polygon.size()); for (const QPoint &point : polygon) poly << mapToScene(point); return poly; @@ -2509,7 +2509,7 @@ QPolygon QGraphicsView::mapFromScene(const QRectF &rect) const QPolygon QGraphicsView::mapFromScene(const QPolygonF &polygon) const { QPolygon poly; - poly.reserve(polygon.count()); + poly.reserve(polygon.size()); for (const QPointF &point : polygon) poly << mapFromScene(point); return poly; @@ -2623,7 +2623,7 @@ void QGraphicsView::updateScene(const QList<QRectF> &rects) // Extract and reset dirty scene rect info. QList<QRect> dirtyViewportRects; - dirtyViewportRects.reserve(d->dirtyRegion.rectCount() + rects.count()); + dirtyViewportRects.reserve(d->dirtyRegion.rectCount() + rects.size()); for (const QRect &dirtyRect : d->dirtyRegion) dirtyViewportRects += dirtyRect; d->dirtyRegion = QRegion(); @@ -2652,7 +2652,7 @@ void QGraphicsView::updateScene(const QList<QRectF> &rects) dirtyViewportRects << xrect; } - for (const QRect &rect : qAsConst(dirtyViewportRects)) { + for (const QRect &rect : std::as_const(dirtyViewportRects)) { // Add the exposed rect to the update region. In rect update // mode, we only count the bounding rect of items. if (!boundingRectUpdate) { @@ -3810,7 +3810,7 @@ bool QGraphicsView::isTransformed() const a view coordinate to a floating point scene coordinate, or mapFromScene() to map from floating point scene coordinates to view coordinates. - \sa transform(), rotate(), scale(), shear(), translate() + \sa transform(), resetTransform(), rotate(), scale(), shear(), translate() */ void QGraphicsView::setTransform(const QTransform &matrix, bool combine ) { diff --git a/src/widgets/graphicsview/qgraphicswidget.cpp b/src/widgets/graphicsview/qgraphicswidget.cpp index f80fc4e4e4..3679723bc4 100644 --- a/src/widgets/graphicsview/qgraphicswidget.cpp +++ b/src/widgets/graphicsview/qgraphicswidget.cpp @@ -199,7 +199,7 @@ QGraphicsWidget::~QGraphicsWidget() Q_D(QGraphicsWidget); #ifndef QT_NO_ACTION // Remove all actions from this widget - for (auto action : qAsConst(d->actions)) { + for (auto action : std::as_const(d->actions)) { QActionPrivate *apriv = action->d_func(); apriv->associatedObjects.removeAll(this); } @@ -1968,7 +1968,7 @@ void QGraphicsWidget::addAction(QAction *action) */ void QGraphicsWidget::addActions(const QList<QAction *> &actions) { - for (int i = 0; i < actions.count(); ++i) + for (int i = 0; i < actions.size(); ++i) insertAction(nullptr, actions.at(i)); } @@ -2025,7 +2025,7 @@ void QGraphicsWidget::insertAction(QAction *before, QAction *action) */ void QGraphicsWidget::insertActions(QAction *before, const QList<QAction *> &actions) { - for (int i = 0; i < actions.count(); ++i) + for (int i = 0; i < actions.size(); ++i) insertAction(before, actions.at(i)); } diff --git a/src/widgets/graphicsview/qsimplex_p.cpp b/src/widgets/graphicsview/qsimplex_p.cpp index 23f63909a5..948437bf68 100644 --- a/src/widgets/graphicsview/qsimplex_p.cpp +++ b/src/widgets/graphicsview/qsimplex_p.cpp @@ -580,7 +580,7 @@ bool QSimplex::simplifyConstraints(QList<QSimplexConstraint *> *constraints) QList<QSimplexConstraint *>::iterator iter = constraints->begin(); while (iter != constraints->end()) { QSimplexConstraint *c = *iter; - if ((c->ratio == QSimplexConstraint::Equal) && (c->variables.count() == 1)) { + if ((c->ratio == QSimplexConstraint::Equal) && (c->variables.size() == 1)) { // Check whether this is a constraint of type Var == K // If so, save its value to "results". QSimplexVariable *variable = c->variables.constBegin().key(); diff --git a/src/widgets/itemviews/qabstractitemdelegate.cpp b/src/widgets/itemviews/qabstractitemdelegate.cpp index c6161a4680..73af3b6b1d 100644 --- a/src/widgets/itemviews/qabstractitemdelegate.cpp +++ b/src/widgets/itemviews/qabstractitemdelegate.cpp @@ -480,12 +480,13 @@ bool QAbstractItemDelegatePrivate::editorEventFilter(QObject *object, QEvent *ev // If the application loses focus while editing, then the focus needs to go back // to the itemview when the editor closes. This ensures that when the application // is active again it will have the focus on the itemview as expected. + QWidget *editorParent = editor->parentWidget(); const bool manuallyFixFocus = (event->type() == QEvent::FocusOut) && !editor->hasFocus() && - editor->parentWidget() && + editorParent && (static_cast<QFocusEvent *>(event)->reason() == Qt::ActiveWindowFocusReason); emit q->closeEditor(editor, QAbstractItemDelegate::NoHint); if (manuallyFixFocus) - editor->parentWidget()->setFocus(); + editorParent->setFocus(); } #ifndef QT_NO_SHORTCUT } else if (event->type() == QEvent::ShortcutOverride) { diff --git a/src/widgets/itemviews/qabstractitemview.cpp b/src/widgets/itemviews/qabstractitemview.cpp index 57139cce61..1d991b1b98 100644 --- a/src/widgets/itemviews/qabstractitemview.cpp +++ b/src/widgets/itemviews/qabstractitemview.cpp @@ -1709,6 +1709,12 @@ bool QAbstractItemView::viewportEvent(QEvent *event) { Q_D(QAbstractItemView); switch (event->type()) { + case QEvent::Paint: + // Similar to pre-painting in QAbstractItemView::event to update scrollbar + // visibility, make sure that all pending layout requests have been executed + // so that the view's data structures are up-to-date before rendering. + d->executePostedLayout(); + break; case QEvent::HoverMove: case QEvent::HoverEnter: d->setHoverIndex(indexAt(static_cast<QHoverEvent*>(event)->position().toPoint())); @@ -1939,7 +1945,9 @@ void QAbstractItemView::mouseReleaseEvent(QMouseEvent *event) } bool click = (index == d->pressedIndex && index.isValid() && !releaseFromDoubleClick); - bool selectedClicked = click && (event->button() == Qt::LeftButton) && d->pressedAlreadySelected; + bool selectedClicked = click && d->pressedAlreadySelected + && (event->button() == Qt::LeftButton) + && (event->modifiers() == Qt::NoModifier); EditTrigger trigger = (selectedClicked ? SelectedClicked : NoEditTriggers); const bool edited = click && !d->pressClosedEditor ? edit(index, trigger, event) : false; @@ -1947,7 +1955,7 @@ void QAbstractItemView::mouseReleaseEvent(QMouseEvent *event) if (d->selectionModel && d->noSelectionOnMousePress) { d->noSelectionOnMousePress = false; - if (!edited && !d->pressClosedEditor) + if (!d->pressClosedEditor) d->selectionModel->select(index, selectionCommand(index, event)); } @@ -2366,11 +2374,12 @@ void QAbstractItemView::keyPressEvent(QKeyEvent *event) #if !defined(QT_NO_CLIPBOARD) && !defined(QT_NO_SHORTCUT) if (event == QKeySequence::Copy) { - QVariant variant; - if (d->model) - variant = d->model->data(currentIndex(), Qt::DisplayRole); - if (variant.canConvert<QString>()) - QGuiApplication::clipboard()->setText(variant.toString()); + const QModelIndex index = currentIndex(); + if (index.isValid() && d->model) { + const QVariant variant = d->model->data(index, Qt::DisplayRole); + if (variant.canConvert<QString>()) + QGuiApplication::clipboard()->setText(variant.toString()); + } event->accept(); } #endif @@ -2829,10 +2838,10 @@ void QAbstractItemView::updateEditorGeometries() //we hide and release the editor outside of the loop because it might change the focus and try //to change the editors hashes. - for (int i = 0; i < editorsToHide.count(); ++i) { + for (int i = 0; i < editorsToHide.size(); ++i) { editorsToHide.at(i)->hide(); } - for (int i = 0; i < editorsToRelease.count(); ++i) { + for (int i = 0; i < editorsToRelease.size(); ++i) { d->releaseEditor(editorsToRelease.at(i)); } } @@ -3053,9 +3062,9 @@ void QAbstractItemView::keyboardSearch(const QString &search) // special case for searches with same key like 'aaaaa' bool sameKey = false; - if (d->keyboardInput.length() > 1) { - int c = d->keyboardInput.count(d->keyboardInput.at(d->keyboardInput.length() - 1)); - sameKey = (c == d->keyboardInput.length()); + if (d->keyboardInput.size() > 1) { + int c = d->keyboardInput.count(d->keyboardInput.at(d->keyboardInput.size() - 1)); + sameKey = (c == d->keyboardInput.size()); if (sameKey) skipRow = true; } @@ -3793,7 +3802,7 @@ void QAbstractItemView::startDrag(Qt::DropActions supportedActions) { Q_D(QAbstractItemView); QModelIndexList indexes = d->selectedDraggableIndexes(); - if (indexes.count() > 0) { + if (indexes.size() > 0) { QMimeData *data = d->model->mimeData(indexes); if (!data) return; @@ -4091,8 +4100,12 @@ QItemSelectionModel::SelectionFlags QAbstractItemView::selectionCommand(const QM if (d->pressedAlreadySelected) return QItemSelectionModel::NoUpdate; break; - case QEvent::KeyPress: case QEvent::MouseButtonRelease: + // clicking into area with no items does nothing + if (!index.isValid()) + return QItemSelectionModel::NoUpdate; + Q_FALLTHROUGH(); + case QEvent::KeyPress: // ctrl-release on selected item deselects if ((keyModifiers & Qt::ControlModifier) && d->selectionModel->isSelected(index)) return QItemSelectionModel::Deselect | d->selectionBehaviorFlags(); @@ -4636,7 +4649,7 @@ QPixmap QAbstractItemViewPrivate::renderToPixmap(const QModelIndexList &indexes, QStyleOptionViewItem option; q->initViewItemOption(&option); option.state |= QStyle::State_Selected; - for (int j = 0; j < paintPairs.count(); ++j) { + for (int j = 0; j < paintPairs.size(); ++j) { option.rect = paintPairs.at(j).rect.translated(-r->topLeft()); const QModelIndex ¤t = paintPairs.at(j).index; adjustViewOptionsForIndex(&option, current); diff --git a/src/widgets/itemviews/qbsptree.cpp b/src/widgets/itemviews/qbsptree.cpp index 13660ee3d9..d75144b1a8 100644 --- a/src/widgets/itemviews/qbsptree.cpp +++ b/src/widgets/itemviews/qbsptree.cpp @@ -40,9 +40,9 @@ void QBspTree::climbTree(const QRect &rect, callback *function, QBspTreeData dat void QBspTree::climbTree(const QRect &area, callback *function, QBspTreeData data, int index) { - if (index >= nodes.count()) { // the index points to a leaf + if (index >= nodes.size()) { // the index points to a leaf Q_ASSERT(!nodes.isEmpty()); - function(leaf(index - nodes.count()), area, visited, data); + function(leaf(index - nodes.size()), area, visited, data); return; } diff --git a/src/widgets/itemviews/qbsptree_p.h b/src/widgets/itemviews/qbsptree_p.h index 83d9055aad..1f00616e87 100644 --- a/src/widgets/itemviews/qbsptree_p.h +++ b/src/widgets/itemviews/qbsptree_p.h @@ -55,7 +55,7 @@ public: void climbTree(const QRect &rect, callback *function, QBspTreeData data); - inline int leafCount() const { return leaves.count(); } + inline int leafCount() const { return leaves.size(); } inline QList<int> &leaf(int i) { return leaves[i]; } inline void insertLeaf(const QRect &r, int i) { climbTree(r, &insert, i, 0); } inline void removeLeaf(const QRect &r, int i) { climbTree(r, &remove, i, 0); } diff --git a/src/widgets/itemviews/qcolumnview.cpp b/src/widgets/itemviews/qcolumnview.cpp index 73748d3af4..040bddb311 100644 --- a/src/widgets/itemviews/qcolumnview.cpp +++ b/src/widgets/itemviews/qcolumnview.cpp @@ -98,7 +98,7 @@ void QColumnView::setResizeGripsVisible(bool visible) if (d->showResizeGrips == visible) return; d->showResizeGrips = visible; - for (int i = 0; i < d->columns.count(); ++i) { + for (int i = 0; i < d->columns.size(); ++i) { QAbstractItemView *view = d->columns[i]; if (visible) { QColumnViewGrip *grip = new QColumnViewGrip(view); @@ -140,7 +140,7 @@ void QColumnView::setRootIndex(const QModelIndex &index) return; d->closeColumns(); - Q_ASSERT(d->columns.count() == 0); + Q_ASSERT(d->columns.size() == 0); QAbstractItemView *view = d->createColumn(index, true); if (view->selectionModel()) @@ -206,7 +206,7 @@ void QColumnView::scrollContentsBy(int dx, int dy) return; dx = isRightToLeft() ? -dx : dx; - for (int i = 0; i < d->columns.count(); ++i) + for (int i = 0; i < d->columns.size(); ++i) d->columns.at(i)->move(d->columns.at(i)->x() + dx, 0); d->offset += dx; QAbstractItemView::scrollContentsBy(dx, dy); @@ -420,7 +420,7 @@ int QColumnView::verticalOffset() const */ QRegion QColumnView::visualRegionForSelection(const QItemSelection &selection) const { - int ranges = selection.count(); + int ranges = selection.size(); if (ranges == 0) return QRect(); @@ -603,7 +603,7 @@ void QColumnViewPrivate::_q_clicked(const QModelIndex &index) Q_Q(QColumnView); QModelIndex parent = index.parent(); QAbstractItemView *columnClicked = nullptr; - for (int column = 0; column < columns.count(); ++column) { + for (int column = 0; column < columns.size(); ++column) { if (columns.at(column)->rootIndex() == parent) { columnClicked = columns[column]; break; @@ -664,16 +664,16 @@ QAbstractItemView *QColumnViewPrivate::createColumn(const QModelIndex &index, bo q->connect(grip, SIGNAL(gripMoved(int)), q, SLOT(_q_gripMoved(int))); } - if (columnSizes.count() > columns.count()) { - view->setGeometry(0, 0, columnSizes.at(columns.count()), viewport->height()); + if (columnSizes.size() > columns.size()) { + view->setGeometry(0, 0, columnSizes.at(columns.size()), viewport->height()); } else { int initialWidth = view->sizeHint().width(); if (q->isRightToLeft()) view->setGeometry(viewport->width() - initialWidth, 0, initialWidth, viewport->height()); else view->setGeometry(0, 0, initialWidth, viewport->height()); - columnSizes.resize(qMax(columnSizes.count(), columns.count() + 1)); - columnSizes[columns.count()] = initialWidth; + columnSizes.resize(qMax(columnSizes.size(), columns.size() + 1)); + columnSizes[columns.size()] = initialWidth; } if (!columns.isEmpty() && columns.constLast()->isHidden()) columns.constLast()->setVisible(true); @@ -826,8 +826,8 @@ void QColumnView::setColumnWidths(const QList<int> &list) { Q_D(QColumnView); int i = 0; - const int listCount = list.count(); - const int count = qMin(listCount, d->columns.count()); + const int listCount = list.size(); + const int count = qMin(listCount, d->columns.size()); for (; i < count; ++i) { d->columns.at(i)->resize(list.at(i), d->columns.at(i)->height()); d->columnSizes[i] = list.at(i); @@ -847,7 +847,7 @@ QList<int> QColumnView::columnWidths() const { Q_D(const QColumnView); QList<int> list; - const int columnCount = d->columns.count(); + const int columnCount = d->columns.size(); list.reserve(columnCount); for (int i = 0; i < columnCount; ++i) list.append(d->columnSizes.at(i)); @@ -984,9 +984,9 @@ void QColumnView::selectAll() QModelIndexList indexList = selectionModel()->selectedIndexes(); QModelIndex parent = rootIndex(); QItemSelection selection; - if (indexList.count() >= 1) + if (indexList.size() >= 1) parent = indexList.at(0).parent(); - if (indexList.count() == 1) { + if (indexList.size() == 1) { parent = indexList.at(0); if (!model()->hasChildren(parent)) parent = parent.parent(); @@ -1039,7 +1039,7 @@ void QColumnViewPrivate::checkColumnCreation(const QModelIndex &parent) if (parent == q_func()->currentIndex() && model->hasChildren(parent)) { //the parent has children and is the current //let's try to find out if there is already a mapping that is good - for (int i = 0; i < columns.count(); ++i) { + for (int i = 0; i < columns.size(); ++i) { QAbstractItemView *view = columns.at(i); if (view->rootIndex() == parent) { if (view == previewColumn) { diff --git a/src/widgets/itemviews/qheaderview.cpp b/src/widgets/itemviews/qheaderview.cpp index 413857bf6c..d074c70940 100644 --- a/src/widgets/itemviews/qheaderview.cpp +++ b/src/widgets/itemviews/qheaderview.cpp @@ -980,7 +980,7 @@ bool QHeaderView::isSectionHidden(int logicalIndex) const int QHeaderView::hiddenSectionCount() const { Q_D(const QHeaderView); - return d->hiddenSectionSize.count(); + return d->hiddenSectionSize.size(); } /*! @@ -1061,7 +1061,7 @@ int QHeaderView::visualIndex(int logicalIndex) const if (d->visualIndices.isEmpty()) { // nothing has been moved, so we have no mapping if (logicalIndex < d->sectionCount()) return logicalIndex; - } else if (logicalIndex < d->visualIndices.count()) { + } else if (logicalIndex < d->visualIndices.size()) { int visual = d->visualIndices.at(logicalIndex); Q_ASSERT(visual < d->sectionCount()); return visual; @@ -1762,22 +1762,27 @@ bool QHeaderView::restoreState(const QByteArray &state) Q_D(QHeaderView); if (state.isEmpty()) return false; - QByteArray data = state; - QDataStream stream(&data, QIODevice::ReadOnly); - stream.setVersion(QDataStream::Qt_5_0); - int marker; - int ver; - stream >> marker; - stream >> ver; - if (stream.status() != QDataStream::Ok + + for (const auto dataStreamVersion : {QDataStream::Qt_5_0, QDataStream::Qt_6_0}) { + + QByteArray data = state; + QDataStream stream(&data, QIODevice::ReadOnly); + stream.setVersion(dataStreamVersion); + int marker; + int ver; + stream >> marker; + stream >> ver; + if (stream.status() != QDataStream::Ok || marker != QHeaderViewPrivate::VersionMarker - || ver != 0) // current version is 0 - return false; + || ver != 0) { // current version is 0 + return false; + } - if (d->read(stream)) { - emit sortIndicatorChanged(d->sortIndicatorSection, d->sortIndicatorOrder ); - d->viewport->update(); - return true; + if (d->read(stream)) { + emit sortIndicatorChanged(d->sortIndicatorSection, d->sortIndicatorOrder ); + d->viewport->update(); + return true; + } } return false; } @@ -1906,10 +1911,10 @@ void QHeaderView::sectionsInserted(const QModelIndex &parent, QHeaderViewPrivate::SectionItem section(d->defaultSectionSize, d->globalResizeMode); d->sectionStartposRecalc = true; - if (d->sectionItems.isEmpty() || insertAt >= d->sectionItems.count()) { + if (d->sectionItems.isEmpty() || insertAt >= d->sectionItems.size()) { int insertLength = d->defaultSectionSize * insertCount; d->length += insertLength; - d->sectionItems.insert(d->sectionItems.count(), insertCount, section); // append + d->sectionItems.insert(d->sectionItems.size(), insertCount, section); // append } else { // separate them out into their own sections int insertLength = d->defaultSectionSize * insertCount; @@ -1932,8 +1937,8 @@ void QHeaderView::sectionsInserted(const QModelIndex &parent, // update mapping if (!d->visualIndices.isEmpty() && !d->logicalIndices.isEmpty()) { - Q_ASSERT(d->visualIndices.count() == d->logicalIndices.count()); - int mappingCount = d->visualIndices.count(); + Q_ASSERT(d->visualIndices.size() == d->logicalIndices.size()); + int mappingCount = d->visualIndices.size(); for (int i = 0; i < mappingCount; ++i) { if (d->visualIndices.at(i) >= logicalFirst) d->visualIndices[i] += insertCount; @@ -2023,7 +2028,7 @@ void QHeaderViewPrivate::_q_sectionsRemoved(const QModelIndex &parent, if (logicalFirst == logicalLast) { // Remove just one index. int l = logicalFirst; int visual = visualIndices.at(l); - Q_ASSERT(sectionCount() == logicalIndices.count()); + Q_ASSERT(sectionCount() == logicalIndices.size()); for (int v = 0; v < sectionCount(); ++v) { if (v > visual) { int logical = logicalIndices.at(v); @@ -2038,17 +2043,17 @@ void QHeaderViewPrivate::_q_sectionsRemoved(const QModelIndex &parent, removeSectionsFromSectionItems(visual, visual); } else { sectionStartposRecalc = true; // We will need to recalc positions after removing items - for (int u = 0; u < sectionItems.count(); ++u) // Store section info + for (int u = 0; u < sectionItems.size(); ++u) // Store section info sectionItems.at(u).tmpLogIdx = logicalIndices.at(u); - for (int v = sectionItems.count() - 1; v >= 0; --v) { // Remove the sections + for (int v = sectionItems.size() - 1; v >= 0; --v) { // Remove the sections if (logicalFirst <= sectionItems.at(v).tmpLogIdx && sectionItems.at(v).tmpLogIdx <= logicalLast) removeSectionsFromSectionItems(v, v); } - visualIndices.resize(sectionItems.count()); - logicalIndices.resize(sectionItems.count()); + visualIndices.resize(sectionItems.size()); + logicalIndices.resize(sectionItems.size()); int* visual_data = visualIndices.data(); int* logical_data = logicalIndices.data(); - for (int w = 0; w < sectionItems.count(); ++w) { // Restore visual and logical indexes + for (int w = 0; w < sectionItems.size(); ++w) { // Restore visual and logical indexes int logindex = sectionItems.at(w).tmpLogIdx; if (logindex > logicalFirst) logindex -= changeCount; @@ -2121,9 +2126,9 @@ void QHeaderViewPrivate::_q_sectionsAboutToBeChanged(const QList<QPersistentMode return; layoutChangePersistentSections.clear(); - layoutChangePersistentSections.reserve(std::min(10, int(sectionItems.count()))); + layoutChangePersistentSections.reserve(std::min(10, int(sectionItems.size()))); // after layoutChanged another section can be last stretched section - if (stretchLastSection && lastSectionLogicalIdx >= 0 && lastSectionLogicalIdx < sectionItems.count()) { + if (stretchLastSection && lastSectionLogicalIdx >= 0 && lastSectionLogicalIdx < sectionItems.size()) { const int visual = visualIndex(lastSectionLogicalIdx); if (visual >= 0 && visual < sectionItems.size()) { auto &itemRef = sectionItems[visual]; @@ -2218,7 +2223,7 @@ void QHeaderViewPrivate::_q_sectionsChanged(const QList<QPersistentModelIndex> & : index.row()); // the new visualIndices are already adjusted / reset by initializeSections() const int newVisualIndex = visualIndex(newLogicalIndex); - if (newVisualIndex < sectionItems.count()) { + if (newVisualIndex < sectionItems.size()) { auto &newSection = sectionItems[newVisualIndex]; newSection = item.section; @@ -2283,7 +2288,7 @@ void QHeaderView::initializeSections(int start, int end) int newCount = end + 1; d->removeSectionsFromSectionItems(newCount, d->sectionCount() - 1); if (!d->hiddenSectionSize.isEmpty()) { - if (oldCount - newCount > d->hiddenSectionSize.count()) { + if (oldCount - newCount > d->hiddenSectionSize.size()) { for (int i = end + 1; i < d->sectionCount(); ++i) d->hiddenSectionSize.remove(i); } else { @@ -3448,7 +3453,7 @@ void QHeaderView::initStyleOption(QStyleOptionFrame *option) const bool QHeaderViewPrivate::isSectionSelected(int section) const { int i = section * 2; - if (i < 0 || i >= sectionSelected.count()) + if (i < 0 || i >= sectionSelected.size()) return false; if (sectionSelected.testBit(i)) // if the value was cached return sectionSelected.testBit(i + 1); @@ -3672,7 +3677,7 @@ void QHeaderViewPrivate::resizeSections(QHeaderView::ResizeMode globalMode, bool void QHeaderViewPrivate::createSectionItems(int start, int end, int sizePerSection, QHeaderView::ResizeMode mode) { - if (end >= sectionItems.count()) { + if (end >= sectionItems.size()) { sectionItems.resize(end + 1); sectionStartposRecalc = true; } @@ -3688,7 +3693,7 @@ void QHeaderViewPrivate::createSectionItems(int start, int end, int sizePerSecti void QHeaderViewPrivate::removeSectionsFromSectionItems(int start, int end) { // remove sections - sectionStartposRecalc |= (end != sectionItems.count() - 1); + sectionStartposRecalc |= (end != sectionItems.size() - 1); int removedlength = 0; for (int u = start; u <= end; ++u) removedlength += sectionItems.at(u).size; @@ -3876,7 +3881,7 @@ void QHeaderViewPrivate::setDefaultSectionSize(int size) customDefaultSectionSize = true; if (state == QHeaderViewPrivate::ResizeSection) preventCursorChangeInSetOffset = true; - for (int i = 0; i < sectionItems.count(); ++i) { + for (int i = 0; i < sectionItems.size(); ++i) { QHeaderViewPrivate::SectionItem §ion = sectionItems[i]; if (hiddenSectionSize.isEmpty() || !isVisualIndexHidden(i)) { // resize on not hidden. const int newSize = size; @@ -3945,7 +3950,7 @@ int QHeaderViewPrivate::headerVisualIndexAt(int position) const if (sectionStartposRecalc) recalcSectionStartPos(); int startidx = 0; - int endidx = sectionItems.count() - 1; + int endidx = sectionItems.size() - 1; while (startidx <= endidx) { int middle = (endidx + startidx) / 2; if (sectionItems.at(middle).calculated_startpos > position) { @@ -3968,7 +3973,7 @@ void QHeaderViewPrivate::setHeaderSectionResizeMode(int visual, QHeaderView::Res QHeaderView::ResizeMode QHeaderViewPrivate::headerSectionResizeMode(int visual) const { - if (visual < 0 || visual >= sectionItems.count()) + if (visual < 0 || visual >= sectionItems.size()) return globalResizeMode; return static_cast<QHeaderView::ResizeMode>(sectionItems.at(visual).resizeMode); } @@ -3976,7 +3981,7 @@ QHeaderView::ResizeMode QHeaderViewPrivate::headerSectionResizeMode(int visual) void QHeaderViewPrivate::setGlobalHeaderResizeMode(QHeaderView::ResizeMode mode) { globalResizeMode = mode; - for (int i = 0; i < sectionItems.count(); ++i) + for (int i = 0; i < sectionItems.size(); ++i) sectionItems[i].resizeMode = mode; } @@ -3995,7 +4000,7 @@ int QHeaderViewPrivate::adjustedVisualIndex(int visualIndex) const if (!hiddenSectionSize.isEmpty()) { int adjustedVisualIndex = visualIndex; int currentVisualIndex = 0; - for (int i = 0; i < sectionItems.count(); ++i) { + for (int i = 0; i < sectionItems.size(); ++i) { if (isVisualIndexHidden(i)) ++adjustedVisualIndex; else @@ -4131,12 +4136,21 @@ bool QHeaderViewPrivate::read(QDataStream &in) in >> global; + // Check parameter consistency + // Global orientation out of bounds? + if (global < 0 || global > QHeaderView::ResizeToContents) + return false; + + // Alignment out of bounds? + if (align < 0 || align > Qt::AlignVertical_Mask) + return false; + in >> sectionItemsIn; // In Qt4 we had a vector of spans where one span could hold information on more sections. // Now we have an itemvector where one items contains information about one section // For backward compatibility with Qt4 we do the following QList<SectionItem> newSectionItems; - for (int u = 0; u < sectionItemsIn.count(); ++u) { + for (int u = 0; u < sectionItemsIn.size(); ++u) { int count = sectionItemsIn.at(u).tmpDataStreamSectionCount; if (count > 1) sectionItemsIn[u].size /= count; @@ -4145,25 +4159,25 @@ bool QHeaderViewPrivate::read(QDataStream &in) } int sectionItemsLengthTotal = 0; - for (const SectionItem §ion : qAsConst(newSectionItems)) + for (const SectionItem §ion : std::as_const(newSectionItems)) sectionItemsLengthTotal += section.size; if (sectionItemsLengthTotal != lengthIn) return false; const int currentCount = (orient == Qt::Horizontal ? model->columnCount(root) : model->rowCount(root)); - if (newSectionItems.count() < currentCount) { + if (newSectionItems.size() < currentCount) { // we have sections not in the saved state, give them default settings if (!visualIndicesIn.isEmpty() && !logicalIndicesIn.isEmpty()) { - for (int i = newSectionItems.count(); i < currentCount; ++i) { + for (int i = newSectionItems.size(); i < currentCount; ++i) { visualIndicesIn.append(i); logicalIndicesIn.append(i); } } - const int insertCount = currentCount - newSectionItems.count(); + const int insertCount = currentCount - newSectionItems.size(); const int insertLength = defaultSectionSizeIn * insertCount; lengthIn += insertLength; SectionItem section(defaultSectionSizeIn, globalResizeMode); - newSectionItems.insert(newSectionItems.count(), insertCount, section); // append + newSectionItems.insert(newSectionItems.size(), insertCount, section); // append } orientation = static_cast<Qt::Orientation>(orient); diff --git a/src/widgets/itemviews/qheaderview_p.h b/src/widgets/itemviews/qheaderview_p.h index fce525166d..c599aeff8d 100644 --- a/src/widgets/itemviews/qheaderview_p.h +++ b/src/widgets/itemviews/qheaderview_p.h @@ -120,12 +120,12 @@ public: inline void prepareSectionSelected() { if (!selectionModel || !selectionModel->hasSelection()) sectionSelected.clear(); - else if (sectionSelected.count() != sectionCount() * 2) + else if (sectionSelected.size() != sectionCount() * 2) sectionSelected.fill(false, sectionCount() * 2); else sectionSelected.fill(false); } - inline int sectionCount() const {return sectionItems.count();} + inline int sectionCount() const {return sectionItems.size();} inline bool reverse() const { return orientation == Qt::Horizontal && q_func()->isRightToLeft(); @@ -166,8 +166,8 @@ public: } inline void initializeIndexMapping() const { - if (visualIndices.count() != sectionCount() - || logicalIndices.count() != sectionCount()) { + if (visualIndices.size() != sectionCount() + || logicalIndices.size() != sectionCount()) { visualIndices.resize(sectionCount()); logicalIndices.resize(sectionCount()); for (int s = 0; s < sectionCount(); ++s) { @@ -178,7 +178,7 @@ public: } inline void clearCascadingSections() { - firstCascadingSection = sectionItems.count(); + firstCascadingSection = sectionItems.size(); lastCascadingSection = 0; cascadingSectionSize.clear(); } @@ -332,7 +332,7 @@ public: void setHiddenSectionsFromBitVector(const QBitArray §ionHidden) { SectionItem *sectionData = sectionItems.data(); - for (int i = 0; i < sectionHidden.count(); ++i) + for (int i = 0; i < sectionHidden.size(); ++i) sectionData[i].isHidden = sectionHidden.at(i); } diff --git a/src/widgets/itemviews/qlistview.cpp b/src/widgets/itemviews/qlistview.cpp index 30bf327af7..b03c1a47f5 100644 --- a/src/widgets/itemviews/qlistview.cpp +++ b/src/widgets/itemviews/qlistview.cpp @@ -891,7 +891,7 @@ void QListView::dropEvent(QDropEvent *event) if (!event->isAccepted() && d->dropOn(event, &row, &col, &topIndex)) { const QList<QModelIndex> selIndexes = selectedIndexes(); QList<QPersistentModelIndex> persIndexes; - persIndexes.reserve(selIndexes.count()); + persIndexes.reserve(selIndexes.size()); for (const auto &index : selIndexes) { persIndexes.append(index); @@ -908,7 +908,7 @@ void QListView::dropEvent(QDropEvent *event) int r = row == -1 ? model()->rowCount() : (dropRow.row() >= 0 ? dropRow.row() : row); bool dataMoved = false; - for (int i = 0; i < persIndexes.count(); ++i) { + for (int i = 0; i < persIndexes.size(); ++i) { const QPersistentModelIndex &pIndex = persIndexes.at(i); if (r != pIndex.row()) { // try to move (preserves selection) @@ -1097,7 +1097,7 @@ QModelIndex QListView::indexAt(const QPoint &p) const Q_D(const QListView); QRect rect(p.x() + horizontalOffset(), p.y() + verticalOffset(), 1, 1); const QList<QModelIndex> intersectVector = d->intersectingSet(rect); - QModelIndex index = intersectVector.count() > 0 + QModelIndex index = intersectVector.size() > 0 ? intersectVector.last() : QModelIndex(); if (index.isValid() && visualRect(index).contains(p)) return index; @@ -2159,7 +2159,7 @@ void QListModeViewBase::dragMoveEvent(QDragMoveEvent *event) QRect rect(p.x() + horizontalOffset(), p.y() + verticalOffset(), 1, 1); rect.adjust(-dd->spacing(), -dd->spacing(), dd->spacing(), dd->spacing()); const QList<QModelIndex> intersectVector = dd->intersectingSet(rect); - QModelIndex index = intersectVector.count() > 0 + QModelIndex index = intersectVector.size() > 0 ? intersectVector.last() : QModelIndex(); dd->hover = index; if (!dd->droppingOnItself(event, index) @@ -2238,7 +2238,7 @@ bool QListModeViewBase::dropOn(QDropEvent *event, int *dropRow, int *dropCol, QM QRect rect(p.x() + horizontalOffset(), p.y() + verticalOffset(), 1, 1); rect.adjust(-dd->spacing(), -dd->spacing(), dd->spacing(), dd->spacing()); const QList<QModelIndex> intersectVector = dd->intersectingSet(rect); - index = intersectVector.count() > 0 + index = intersectVector.size() > 0 ? intersectVector.last() : QModelIndex(); if (!index.isValid()) index = dd->root; @@ -2284,7 +2284,7 @@ void QListModeViewBase::updateVerticalScrollBar(const QSize &step) if (verticalScrollMode() == QAbstractItemView::ScrollPerItem && ((flow() == QListView::TopToBottom && !isWrapping()) || (flow() == QListView::LeftToRight && isWrapping()))) { - const int steps = (flow() == QListView::TopToBottom ? scrollValueMap : segmentPositions).count() - 1; + const int steps = (flow() == QListView::TopToBottom ? scrollValueMap : segmentPositions).size() - 1; if (steps > 0) { const int pageSteps = perItemScrollingPageSteps(viewport()->height(), contentsSize.height(), isWrapping()); verticalScrollBar()->setSingleStep(1); @@ -2305,7 +2305,7 @@ void QListModeViewBase::updateHorizontalScrollBar(const QSize &step) if (horizontalScrollMode() == QAbstractItemView::ScrollPerItem && ((flow() == QListView::TopToBottom && isWrapping()) || (flow() == QListView::LeftToRight && !isWrapping()))) { - int steps = (flow() == QListView::TopToBottom ? segmentPositions : scrollValueMap).count() - 1; + int steps = (flow() == QListView::TopToBottom ? segmentPositions : scrollValueMap).size() - 1; if (steps > 0) { const int pageSteps = perItemScrollingPageSteps(viewport()->width(), contentsSize.width(), isWrapping()); horizontalScrollBar()->setSingleStep(1); @@ -2329,10 +2329,10 @@ int QListModeViewBase::verticalScrollToValue(int index, QListView::ScrollHint hi } else { int scrollBarValue = verticalScrollBar()->value(); int numHidden = 0; - for (const auto &idx : qAsConst(dd->hiddenRows)) + for (const auto &idx : std::as_const(dd->hiddenRows)) if (idx.row() <= scrollBarValue) ++numHidden; - value = qBound(0, scrollValueMap.at(verticalScrollBar()->value()) - numHidden, flowPositions.count() - 1); + value = qBound(0, scrollValueMap.at(verticalScrollBar()->value()) - numHidden, flowPositions.size() - 1); } if (above) hint = QListView::PositionAtTop; @@ -2352,7 +2352,7 @@ int QListModeViewBase::horizontalOffset() const if (horizontalScrollMode() == QAbstractItemView::ScrollPerItem) { if (isWrapping()) { if (flow() == QListView::TopToBottom && !segmentPositions.isEmpty()) { - const int max = segmentPositions.count() - 1; + const int max = segmentPositions.size() - 1; int currentValue = qBound(0, horizontalScrollBar()->value(), max); int position = segmentPositions.at(currentValue); int maximumValue = qBound(0, horizontalScrollBar()->maximum(), max); @@ -2374,13 +2374,13 @@ int QListModeViewBase::verticalOffset() const if (isWrapping()) { if (flow() == QListView::LeftToRight && !segmentPositions.isEmpty()) { int value = verticalScrollBar()->value(); - if (value >= segmentPositions.count()) + if (value >= segmentPositions.size()) return 0; return segmentPositions.at(value) - spacing(); } } else if (flow() == QListView::TopToBottom && !flowPositions.isEmpty()) { int value = verticalScrollBar()->value(); - if (value > scrollValueMap.count()) + if (value > scrollValueMap.size()) return 0; return flowPositions.at(scrollValueMap.at(value)) - spacing(); } @@ -2398,7 +2398,7 @@ int QListModeViewBase::horizontalScrollToValue(int index, QListView::ScrollHint if (scrollValueMap.isEmpty()) value = 0; else - value = qBound(0, scrollValueMap.at(horizontalScrollBar()->value()), flowPositions.count() - 1); + value = qBound(0, scrollValueMap.at(horizontalScrollBar()->value()), flowPositions.size() - 1); if (leftOf) hint = QListView::PositionAtTop; else if (rightOf) @@ -2420,7 +2420,7 @@ void QListModeViewBase::scrollContentsBy(int dx, int dy, bool scrollElasticBand) if (isWrapping()) { if (segmentPositions.isEmpty()) return; - const int max = segmentPositions.count() - 1; + const int max = segmentPositions.size() - 1; if (horizontal && flow() == QListView::TopToBottom && dx != 0) { int currentValue = qBound(0, horizontalValue, max); int previousValue = qBound(0, currentValue + dx, max); @@ -2437,7 +2437,7 @@ void QListModeViewBase::scrollContentsBy(int dx, int dy, bool scrollElasticBand) } else { if (flowPositions.isEmpty()) return; - const int max = scrollValueMap.count() - 1; + const int max = scrollValueMap.size() - 1; if (vertical && flow() == QListView::TopToBottom && dy != 0) { int currentValue = qBound(0, verticalValue, max); int previousValue = qBound(0, currentValue + dy, max); @@ -2465,11 +2465,11 @@ QListViewItem QListModeViewBase::indexToListViewItem(const QModelIndex &index) c { if (flowPositions.isEmpty() || segmentPositions.isEmpty() - || index.row() >= flowPositions.count() - 1) + || index.row() >= flowPositions.size() - 1) return QListViewItem(); const int segment = qBinarySearch<int>(segmentStartRows, index.row(), - 0, segmentStartRows.count() - 1); + 0, segmentStartRows.size() - 1); QStyleOptionViewItem options; @@ -2487,7 +2487,7 @@ QListViewItem QListModeViewBase::indexToListViewItem(const QModelIndex &index) c pos.setY(flowPositions.at(index.row())); pos.setX(segmentPositions.at(segment)); if (isWrapping()) { // make the items as wide as the segment - int right = (segment + 1 >= segmentPositions.count() + int right = (segment + 1 >= segmentPositions.size() ? contentsSize.width() : segmentPositions.at(segment + 1)); cellSize.setWidth(right - pos.x()); @@ -2611,7 +2611,7 @@ void QListModeViewBase::doStaticLayout(const QListViewLayoutInfo &info) deltaSegPosition = 0; } // save the flow position of this item - scrollValueMap.append(flowPositions.count()); + scrollValueMap.append(flowPositions.size()); flowPositions.append(flowPosition); // prepare for the next item deltaSegPosition = qMax(deltaSegHint, deltaSegPosition); @@ -2627,17 +2627,17 @@ void QListModeViewBase::doStaticLayout(const QListViewLayoutInfo &info) // set the contents size QRect rect = info.bounds; if (info.flow == QListView::LeftToRight) { - rect.setRight(segmentPositions.count() == 1 ? flowPosition : info.bounds.right()); + rect.setRight(segmentPositions.size() == 1 ? flowPosition : info.bounds.right()); rect.setBottom(segPosition + deltaSegPosition); } else { // TopToBottom rect.setRight(segPosition + deltaSegPosition); - rect.setBottom(segmentPositions.count() == 1 ? flowPosition : info.bounds.bottom()); + rect.setBottom(segmentPositions.size() == 1 ? flowPosition : info.bounds.bottom()); } contentsSize = QSize(rect.right(), rect.bottom()); // if it is the last batch, save the end of the segments if (info.last == info.max) { segmentExtents.append(flowPosition); - scrollValueMap.append(flowPositions.count()); + scrollValueMap.append(flowPositions.size()); flowPositions.append(flowPosition); segmentPositions.append(info.wrap ? segPosition + deltaSegPosition : INT_MAX); } @@ -2670,10 +2670,10 @@ QList<QModelIndex> QListModeViewBase::intersectingSet(const QRect &area) const flowStartPosition = area.top(); flowEndPosition = area.bottom(); } - if (segmentPositions.count() < 2 || flowPositions.isEmpty()) + if (segmentPositions.size() < 2 || flowPositions.isEmpty()) return ret; // the last segment position is actually the edge of the last segment - const int segLast = segmentPositions.count() - 2; + const int segLast = segmentPositions.size() - 2; int seg = qBinarySearch<int>(segmentPositions, segStartPosition, 0, segLast + 1); for (; seg <= segLast && segmentPositions.at(seg) <= segEndPosition; ++seg) { int first = segmentStartRows.at(seg); @@ -2740,15 +2740,15 @@ int QListModeViewBase::perItemScrollingPageSteps(int length, int bounds, bool wr positions.append(flowPositions.at(itemShown)); } if (positions.isEmpty() || bounds <= length) - return positions.count(); + return positions.size(); if (uniformItemSizes()) { - for (int i = 1; i < positions.count(); ++i) + for (int i = 1; i < positions.size(); ++i) if (positions.at(i) > 0) return length / positions.at(i); return 0; // all items had height 0 } int pageSteps = 0; - int steps = positions.count() - 1; + int steps = positions.size() - 1; int max = qMax(length, bounds); int min = qMin(length, bounds); int pos = min - (max - positions.constLast()); @@ -2810,7 +2810,7 @@ int QListModeViewBase::perItemScrollToValue(int index, int scrollValue, int view // ### wrapped scrolling in the flow direction return flowPositions.at(index + hiddenRowsBefore); // ### always pixel based for now } else if (!segmentStartRows.isEmpty()) { // we are scrolling in the "segment" direction - int segment = qBinarySearch<int>(segmentStartRows, index, 0, segmentStartRows.count() - 1); + int segment = qBinarySearch<int>(segmentStartRows, index, 0, segmentStartRows.size() - 1); int leftSegment = segment; const int rightSegment = leftSegment; const int bottomCoordinate = segmentPositions.at(segment); @@ -2853,7 +2853,7 @@ void QListModeViewBase::clear() void QIconModeViewBase::setPositionForIndex(const QPoint &position, const QModelIndex &index) { - if (index.row() >= items.count()) + if (index.row() >= items.size()) return; const QSize oldContents = contentsSize; qq->update(index); // update old position @@ -2866,7 +2866,7 @@ void QIconModeViewBase::setPositionForIndex(const QPoint &position, const QModel void QIconModeViewBase::appendHiddenRow(int row) { - if (row >= 0 && row < items.count()) //remove item + if (row >= 0 && row < items.size()) //remove item tree.removeLeaf(items.at(row).rect(), row); QCommonListViewBase::appendHiddenRow(row); } @@ -2874,7 +2874,7 @@ void QIconModeViewBase::appendHiddenRow(int row) void QIconModeViewBase::removeHiddenRow(int row) { QCommonListViewBase::removeHiddenRow(row); - if (row >= 0 && row < items.count()) //insert item + if (row >= 0 && row < items.size()) //insert item tree.insertLeaf(items.at(row).rect(), row); } @@ -2885,7 +2885,7 @@ bool QIconModeViewBase::filterStartDrag(Qt::DropActions supportedActions) // plus adding viewitems to the draggedItems list. // We need these items to draw the drag items QModelIndexList indexes = dd->selectionModel->selectedIndexes(); - if (indexes.count() > 0 ) { + if (indexes.size() > 0 ) { if (viewport()->acceptDrops()) { QModelIndexList::ConstIterator it = indexes.constBegin(); for (; it != indexes.constEnd(); ++it) @@ -2990,7 +2990,7 @@ bool QIconModeViewBase::filterDragMoveEvent(QDragMoveEvent *e) if (movement() == QListView::Snap) { QRect rect(snapToGrid(e->position().toPoint() + offset()), gridSize()); const QList<QModelIndex> intersectVector = intersectingSet(rect); - index = intersectVector.count() > 0 ? intersectVector.last() : QModelIndex(); + index = intersectVector.size() > 0 ? intersectVector.last() : QModelIndex(); } else { index = qq->indexAt(e->position().toPoint()); } @@ -3029,7 +3029,7 @@ void QIconModeViewBase::dataChanged(const QModelIndex &topLeft, const QModelInde if (column() >= topLeft.column() && column() <= bottomRight.column()) { QStyleOptionViewItem option; initViewItemOption(&option); - const int bottom = qMin(items.count(), bottomRight.row() + 1); + const int bottom = qMin(items.size(), bottomRight.row() + 1); const bool useItemSize = !dd->grid.isValid(); for (int row = topLeft.row(); row < bottom; ++row) { @@ -3046,11 +3046,11 @@ void QIconModeViewBase::dataChanged(const QModelIndex &topLeft, const QModelInde bool QIconModeViewBase::doBatchedItemLayout(const QListViewLayoutInfo &info, int max) { - if (info.last >= items.count()) { + if (info.last >= items.size()) { //first we create the items QStyleOptionViewItem option; initViewItemOption(&option); - for (int row = items.count(); row <= info.last; ++row) { + for (int row = items.size(); row <= info.last; ++row) { QSize size = itemSize(option, modelIndex(row)); QListViewItem item(QRect(0, 0, size.width(), size.height()), row); // default pos items.append(item); @@ -3062,7 +3062,7 @@ bool QIconModeViewBase::doBatchedItemLayout(const QListViewLayoutInfo &info, int QListViewItem QIconModeViewBase::indexToListViewItem(const QModelIndex &index) const { - if (index.isValid() && index.row() < items.count()) + if (index.isValid() && index.row() < items.size()) return items.at(index.row()); return QListViewItem(); } @@ -3140,8 +3140,8 @@ void QIconModeViewBase::doDynamicLayout(const QListViewLayoutInfo &info) segPosition = topLeft.x(); } - if (moved.count() != items.count()) - moved.resize(items.count()); + if (moved.size() != items.size()) + moved.resize(items.size()); QRect rect(QPoint(), topLeft); QListViewItem *item = nullptr; @@ -3269,15 +3269,15 @@ int QIconModeViewBase::itemIndex(const QListViewItem &item) const if (!item.isValid()) return -1; int i = item.indexHint; - if (i < items.count()) { + if (i < items.size()) { if (items.at(i) == item) return i; } else { - i = items.count() - 1; + i = items.size() - 1; } int j = i; - int c = items.count(); + int c = items.size(); bool a = true; bool b = true; @@ -3305,9 +3305,9 @@ void QIconModeViewBase::addLeaf(QList<int> &leaf, const QRect &area, uint visite { QListViewItem *vi; QIconModeViewBase *_this = static_cast<QIconModeViewBase *>(data.ptr); - for (int i = 0; i < leaf.count(); ++i) { + for (int i = 0; i < leaf.size(); ++i) { int idx = leaf.at(i); - if (idx < 0 || idx >= _this->items.count()) + if (idx < 0 || idx >= _this->items.size()) continue; vi = &_this->items[idx]; Q_ASSERT(vi); @@ -3335,8 +3335,8 @@ void QIconModeViewBase::moveItem(int index, const QPoint &dest) contentsSize = (QRect(QPoint(0, 0), contentsSize)|QRect(dest, rect.size())).size(); // mark the item as moved - if (moved.count() != items.count()) - moved.resize(items.count()); + if (moved.size() != items.size()) + moved.resize(items.size()); moved.setBit(index, true); } @@ -3388,7 +3388,7 @@ void QIconModeViewBase::clear() void QIconModeViewBase::updateContentsSize() { QRect bounding; - for (int i = 0; i < items.count(); ++i) + for (int i = 0; i < items.size(); ++i) bounding |= items.at(i).rect(); contentsSize = bounding.size(); } @@ -3398,6 +3398,7 @@ void QIconModeViewBase::updateContentsSize() */ void QListView::currentChanged(const QModelIndex ¤t, const QModelIndex &previous) { + QAbstractItemView::currentChanged(current, previous); #if QT_CONFIG(accessibility) if (QAccessible::isActive()) { if (current.isValid()) { @@ -3408,7 +3409,6 @@ void QListView::currentChanged(const QModelIndex ¤t, const QModelIndex &pr } } #endif - QAbstractItemView::currentChanged(current, previous); } /*! @@ -3445,7 +3445,7 @@ int QListView::visualIndex(const QModelIndex &index) const d->executePostedLayout(); QListViewItem itm = d->indexToListViewItem(index); int visualIndex = d->commonListView->itemIndex(itm); - for (const auto &idx : qAsConst(d->hiddenRows)) { + for (const auto &idx : std::as_const(d->hiddenRows)) { if (idx.row() <= index.row()) --visualIndex; } diff --git a/src/widgets/itemviews/qlistview_p.h b/src/widgets/itemviews/qlistview_p.h index 2095d596ab..de928bbb28 100644 --- a/src/widgets/itemviews/qlistview_p.h +++ b/src/widgets/itemviews/qlistview_p.h @@ -460,7 +460,7 @@ inline QAbstractItemDelegate *QCommonListViewBase::delegate(const QModelIndex &i { return qq->itemDelegateForIndex(idx); } inline bool QCommonListViewBase::isHidden(int row) const { return dd->isHidden(row); } -inline int QCommonListViewBase::hiddenCount() const { return dd->hiddenRows.count(); } +inline int QCommonListViewBase::hiddenCount() const { return dd->hiddenRows.size(); } inline bool QCommonListViewBase::isRightToLeft() const { return qq->isRightToLeft(); } diff --git a/src/widgets/itemviews/qlistwidget.cpp b/src/widgets/itemviews/qlistwidget.cpp index 5080ab8fc5..cc0ccf84da 100644 --- a/src/widgets/itemviews/qlistwidget.cpp +++ b/src/widgets/itemviews/qlistwidget.cpp @@ -36,7 +36,7 @@ QListModel::~QListModel() void QListModel::clear() { beginResetModel(); - for (int i = 0; i < items.count(); ++i) { + for (int i = 0; i < items.size(); ++i) { if (items.at(i)) { items.at(i)->d->theid = -1; items.at(i)->view = nullptr; @@ -80,8 +80,8 @@ void QListModel::insert(int row, QListWidgetItem *item) } else { if (row < 0) row = 0; - else if (row > items.count()) - row = items.count(); + else if (row > items.size()) + row = items.size(); } beginInsertRows(QModelIndex(), row, row); items.insert(row, item); @@ -91,7 +91,7 @@ void QListModel::insert(int row, QListWidgetItem *item) void QListModel::insert(int row, const QStringList &labels) { - const int count = labels.count(); + const int count = labels.size(); if (count <= 0) return; QListWidget *view = qobject_cast<QListWidget*>(QObject::parent()); @@ -104,8 +104,8 @@ void QListModel::insert(int row, const QStringList &labels) } else { if (row < 0) row = 0; - else if (row > items.count()) - row = items.count(); + else if (row > items.size()) + row = items.size(); beginInsertRows(QModelIndex(), row, row + count - 1); for (int i = 0; i < count; ++i) { QListWidgetItem *item = new QListWidgetItem(labels.at(i)); @@ -119,7 +119,7 @@ void QListModel::insert(int row, const QStringList &labels) QListWidgetItem *QListModel::take(int row) { - if (row < 0 || row >= items.count()) + if (row < 0 || row >= items.size()) return nullptr; beginRemoveRows(QModelIndex(), row, row); @@ -133,8 +133,8 @@ QListWidgetItem *QListModel::take(int row) void QListModel::move(int srcRow, int dstRow) { if (srcRow == dstRow - || srcRow < 0 || srcRow >= items.count() - || dstRow < 0 || dstRow > items.count()) + || srcRow < 0 || srcRow >= items.size() + || dstRow < 0 || dstRow > items.size()) return; if (!beginMoveRows(QModelIndex(), srcRow, srcRow, QModelIndex(), dstRow)) @@ -147,7 +147,7 @@ void QListModel::move(int srcRow, int dstRow) int QListModel::rowCount(const QModelIndex &parent) const { - return parent.isValid() ? 0 : items.count(); + return parent.isValid() ? 0 : items.size(); } QModelIndex QListModel::index(const QListWidgetItem *item_) const @@ -158,7 +158,7 @@ QModelIndex QListModel::index(const QListWidgetItem *item_) const return QModelIndex(); int row; const int theid = item->d->theid; - if (theid >= 0 && theid < items.count() && items.at(theid) == item) { + if (theid >= 0 && theid < items.size() && items.at(theid) == item) { row = theid; } else { // we need to search for the item row = items.lastIndexOf(item); // lastIndexOf is an optimization in favor of indexOf @@ -178,14 +178,14 @@ QModelIndex QListModel::index(int row, int column, const QModelIndex &parent) co QVariant QListModel::data(const QModelIndex &index, int role) const { - if (!index.isValid() || index.row() >= items.count()) + if (!index.isValid() || index.row() >= items.size()) return QVariant(); return items.at(index.row())->data(role); } bool QListModel::setData(const QModelIndex &index, const QVariant &value, int role) { - if (!index.isValid() || index.row() >= items.count()) + if (!index.isValid() || index.row() >= items.size()) return false; items.at(index.row())->setData(role, value); return true; @@ -208,10 +208,10 @@ bool QListModel::clearItemData(const QModelIndex &index) QMap<int, QVariant> QListModel::itemData(const QModelIndex &index) const { QMap<int, QVariant> roles; - if (!index.isValid() || index.row() >= items.count()) + if (!index.isValid() || index.row() >= items.size()) return roles; QListWidgetItem *itm = items.at(index.row()); - for (int i = 0; i < itm->d->values.count(); ++i) { + for (int i = 0; i < itm->d->values.size(); ++i) { roles.insert(itm->d->values.at(i).role, itm->d->values.at(i).value); } @@ -288,7 +288,7 @@ bool QListModel::moveRows(const QModelIndex &sourceParent, int sourceRow, int co Qt::ItemFlags QListModel::flags(const QModelIndex &index) const { - if (!index.isValid() || index.row() >= items.count() || index.model() != this) + if (!index.isValid() || index.row() >= items.size() || index.model() != this) return Qt::ItemIsDropEnabled; // we allow drops outside the items return items.at(index.row())->flags(); } @@ -300,8 +300,8 @@ void QListModel::sort(int column, Qt::SortOrder order) emit layoutAboutToBeChanged({}, QAbstractItemModel::VerticalSortHint); - QList<QPair<QListWidgetItem *, int>> sorting(items.count()); - for (int i = 0; i < items.count(); ++i) { + QList<QPair<QListWidgetItem *, int>> sorting(items.size()); + for (int i = 0; i < items.size(); ++i) { QListWidgetItem *item = items.at(i); sorting[i].first = item; sorting[i].second = i; @@ -311,7 +311,7 @@ void QListModel::sort(int column, Qt::SortOrder order) std::sort(sorting.begin(), sorting.end(), compare); QModelIndexList fromIndexes; QModelIndexList toIndexes; - const int sortingCount = sorting.count(); + const int sortingCount = sorting.size(); fromIndexes.reserve(sortingCount); toIndexes.reserve(sortingCount); for (int r = 0; r < sortingCount; ++r) { @@ -376,7 +376,7 @@ void QListModel::ensureSorted(int column, Qt::SortOrder order, int start, int en else if (oldRow > otherRow && newRow <= otherRow) ++sorting[j].second; } - for (int k = 0; k < newPersistentIndexes.count(); ++k) { + for (int k = 0; k < newPersistentIndexes.size(); ++k) { QModelIndex pi = newPersistentIndexes.at(k); int oldPersistentRow = pi.row(); int newPersistentRow = oldPersistentRow; @@ -444,7 +444,7 @@ QMimeData *QListModel::internalMimeData() const QMimeData *QListModel::mimeData(const QModelIndexList &indexes) const { QList<QListWidgetItem*> itemlist; - const int indexesCount = indexes.count(); + const int indexesCount = indexes.size(); itemlist.reserve(indexesCount); for (int i = 0; i < indexesCount; ++i) itemlist << at(indexes.at(i).row()); @@ -465,7 +465,7 @@ bool QListModel::dropMimeData(const QMimeData *data, Qt::DropAction action, if (index.isValid()) row = index.row(); else if (row == -1) - row = items.count(); + row = items.size(); return view->dropMimeData(row, data, action); } @@ -702,7 +702,7 @@ void QListWidgetItem::setData(int role, const QVariant &value) { bool found = false; role = (role == Qt::EditRole ? Qt::DisplayRole : role); - for (int i = 0; i < d->values.count(); ++i) { + for (int i = 0; i < d->values.size(); ++i) { if (d->values.at(i).role == role) { if (d->values.at(i).value == value) return; @@ -730,7 +730,7 @@ void QListWidgetItem::setData(int role, const QVariant &value) QVariant QListWidgetItem::data(int role) const { role = (role == Qt::EditRole ? Qt::DisplayRole : role); - for (int i = 0; i < d->values.count(); ++i) + for (int i = 0; i < d->values.size(); ++i) if (d->values.at(i).role == role) return d->values.at(i).value; return QVariant(); @@ -1760,7 +1760,7 @@ QList<QListWidgetItem*> QListWidget::selectedItems() const Q_D(const QListWidget); QModelIndexList indexes = selectionModel()->selectedIndexes(); QList<QListWidgetItem*> items; - const int numIndexes = indexes.count(); + const int numIndexes = indexes.size(); items.reserve(numIndexes); for (int i = 0; i < numIndexes; ++i) items.append(d->listModel()->at(indexes.at(i).row())); @@ -1837,7 +1837,7 @@ QMimeData *QListWidget::mimeData(const QList<QListWidgetItem *> &items) const // if non empty, it's called from the model's own mimeData if (cachedIndexes.isEmpty()) { - cachedIndexes.reserve(items.count()); + cachedIndexes.reserve(items.size()); for (QListWidgetItem *item : items) cachedIndexes << indexFromItem(item); diff --git a/src/widgets/itemviews/qstyleditemdelegate.cpp b/src/widgets/itemviews/qstyleditemdelegate.cpp index fc8a9203d9..7442fc58c8 100644 --- a/src/widgets/itemviews/qstyleditemdelegate.cpp +++ b/src/widgets/itemviews/qstyleditemdelegate.cpp @@ -115,7 +115,7 @@ public: \row \li \l Qt::AccessibleDescriptionRole \li QString \row \li \l Qt::AccessibleTextRole \li QString \endomit - \row \li \l Qt::BackgroundRole \li QBrush (\since 4.2) + \row \li \l Qt::BackgroundRole \li QBrush \since 4.2 \row \li \l Qt::CheckStateRole \li Qt::CheckState \row \li \l Qt::DecorationRole \li QIcon, QPixmap, QImage and QColor \row \li \l Qt::DisplayRole \li QString and types with a string representation @@ -126,7 +126,7 @@ public: \row \li \l Qt::StatusTipRole \li \endomit \row \li \l Qt::TextAlignmentRole \li Qt::Alignment - \row \li \l Qt::ForegroundRole \li QBrush (\since 4.2) + \row \li \l Qt::ForegroundRole \li QBrush \since 4.2 \omit \row \li \l Qt::ToolTipRole \row \li \l Qt::WhatsThisRole diff --git a/src/widgets/itemviews/qtableview.cpp b/src/widgets/itemviews/qtableview.cpp index 2f46842712..cfde93a477 100644 --- a/src/widgets/itemviews/qtableview.cpp +++ b/src/widgets/itemviews/qtableview.cpp @@ -907,7 +907,7 @@ void QTableViewPrivate::drawAndClipSpans(const QRegion &area, QPainter *painter, } } - for (QSpanCollection::Span *span : qAsConst(visibleSpans)) { + for (QSpanCollection::Span *span : std::as_const(visibleSpans)) { int row = span->top(); int col = span->left(); QModelIndex index = model->index(row, col, root); @@ -2197,7 +2197,7 @@ QModelIndexList QTableView::selectedIndexes() const QModelIndexList modelSelected; if (d->selectionModel) modelSelected = d->selectionModel->selectedIndexes(); - for (int i = 0; i < modelSelected.count(); ++i) { + for (int i = 0; i < modelSelected.size(); ++i) { QModelIndex index = modelSelected.at(i); if (!isIndexHidden(index) && index.parent() == d->root) viewSelected.append(index); diff --git a/src/widgets/itemviews/qtablewidget.cpp b/src/widgets/itemviews/qtablewidget.cpp index ae523b2dda..67886be94f 100644 --- a/src/widgets/itemviews/qtablewidget.cpp +++ b/src/widgets/itemviews/qtablewidget.cpp @@ -27,12 +27,12 @@ QTableModel::~QTableModel() bool QTableModel::insertRows(int row, int count, const QModelIndex &) { - if (count < 1 || row < 0 || row > verticalHeaderItems.count()) + if (count < 1 || row < 0 || row > verticalHeaderItems.size()) return false; beginInsertRows(QModelIndex(), row, row + count - 1); - int rc = verticalHeaderItems.count(); - int cc = horizontalHeaderItems.count(); + int rc = verticalHeaderItems.size(); + int cc = horizontalHeaderItems.size(); verticalHeaderItems.insert(row, count, 0); if (rc == 0) tableItems.resize(cc * count); @@ -44,12 +44,12 @@ bool QTableModel::insertRows(int row, int count, const QModelIndex &) bool QTableModel::insertColumns(int column, int count, const QModelIndex &) { - if (count < 1 || column < 0 || column > horizontalHeaderItems.count()) + if (count < 1 || column < 0 || column > horizontalHeaderItems.size()) return false; beginInsertColumns(QModelIndex(), column, column + count - 1); - int rc = verticalHeaderItems.count(); - int cc = horizontalHeaderItems.count(); + int rc = verticalHeaderItems.size(); + int cc = horizontalHeaderItems.size(); horizontalHeaderItems.insert(column, count, 0); if (cc == 0) tableItems.resize(rc * count); @@ -62,7 +62,7 @@ bool QTableModel::insertColumns(int column, int count, const QModelIndex &) bool QTableModel::removeRows(int row, int count, const QModelIndex &) { - if (count < 1 || row < 0 || row + count > verticalHeaderItems.count()) + if (count < 1 || row < 0 || row + count > verticalHeaderItems.size()) return false; beginRemoveRows(QModelIndex(), row, row + count - 1); @@ -89,7 +89,7 @@ bool QTableModel::removeRows(int row, int count, const QModelIndex &) bool QTableModel::removeColumns(int column, int count, const QModelIndex &) { - if (count < 1 || column < 0 || column + count > horizontalHeaderItems.count()) + if (count < 1 || column < 0 || column + count > horizontalHeaderItems.size()) return false; beginRemoveColumns(QModelIndex(), column, column + count - 1); @@ -118,7 +118,7 @@ bool QTableModel::removeColumns(int column, int count, const QModelIndex &) void QTableModel::setItem(int row, int column, QTableWidgetItem *item) { int i = tableIndex(row, column); - if (i < 0 || i >= tableItems.count()) + if (i < 0 || i >= tableItems.size()) return; QTableWidgetItem *oldItem = tableItems.at(i); if (item == oldItem) @@ -141,12 +141,12 @@ void QTableModel::setItem(int row, int column, QTableWidgetItem *item) // sorted insertion Qt::SortOrder order = view->horizontalHeader()->sortIndicatorOrder(); QList<QTableWidgetItem *> colItems = columnItems(column); - if (row < colItems.count()) + if (row < colItems.size()) colItems.remove(row); int sortedRow; if (item == nullptr) { // move to after all non-0 (sortable) items - sortedRow = colItems.count(); + sortedRow = colItems.size(); } else { QList<QTableWidgetItem *>::iterator it; it = sortedInsertionIterator(colItems.begin(), colItems.end(), order, item); @@ -234,7 +234,7 @@ void QTableModel::removeItem(QTableWidgetItem *item) void QTableModel::setHorizontalHeaderItem(int section, QTableWidgetItem *item) { - if (section < 0 || section >= horizontalHeaderItems.count()) + if (section < 0 || section >= horizontalHeaderItems.size()) return; QTableWidgetItem *oldItem = horizontalHeaderItems.at(section); if (item == oldItem) @@ -256,7 +256,7 @@ void QTableModel::setHorizontalHeaderItem(int section, QTableWidgetItem *item) void QTableModel::setVerticalHeaderItem(int section, QTableWidgetItem *item) { - if (section < 0 || section >= verticalHeaderItems.count()) + if (section < 0 || section >= verticalHeaderItems.size()) return; QTableWidgetItem *oldItem = verticalHeaderItems.at(section); if (item == oldItem) @@ -278,7 +278,7 @@ void QTableModel::setVerticalHeaderItem(int section, QTableWidgetItem *item) QTableWidgetItem *QTableModel::takeHorizontalHeaderItem(int section) { - if (section < 0 || section >= horizontalHeaderItems.count()) + if (section < 0 || section >= horizontalHeaderItems.size()) return nullptr; QTableWidgetItem *itm = horizontalHeaderItems.at(section); if (itm) { @@ -291,7 +291,7 @@ QTableWidgetItem *QTableModel::takeHorizontalHeaderItem(int section) QTableWidgetItem *QTableModel::takeVerticalHeaderItem(int section) { - if (section < 0 || section >= verticalHeaderItems.count()) + if (section < 0 || section >= verticalHeaderItems.size()) return nullptr; QTableWidgetItem *itm = verticalHeaderItems.at(section); if (itm) { @@ -318,7 +318,7 @@ QModelIndex QTableModel::index(const QTableWidgetItem *item) const return QModelIndex(); int i = -1; const int id = item->d->id; - if (id >= 0 && id < tableItems.count() && tableItems.at(id) == item) { + if (id >= 0 && id < tableItems.size() && tableItems.at(id) == item) { i = id; } else { // we need to search for the item i = tableItems.indexOf(const_cast<QTableWidgetItem*>(item)); @@ -332,7 +332,7 @@ QModelIndex QTableModel::index(const QTableWidgetItem *item) const void QTableModel::setRowCount(int rows) { - int rc = verticalHeaderItems.count(); + int rc = verticalHeaderItems.size(); if (rows < 0 || rc == rows) return; if (rc < rows) @@ -343,7 +343,7 @@ void QTableModel::setRowCount(int rows) void QTableModel::setColumnCount(int columns) { - int cc = horizontalHeaderItems.count(); + int cc = horizontalHeaderItems.size(); if (columns < 0 || cc == columns) return; if (cc < columns) @@ -354,12 +354,12 @@ void QTableModel::setColumnCount(int columns) int QTableModel::rowCount(const QModelIndex &parent) const { - return parent.isValid() ? 0 : verticalHeaderItems.count(); + return parent.isValid() ? 0 : verticalHeaderItems.size(); } int QTableModel::columnCount(const QModelIndex &parent) const { - return parent.isValid() ? 0 : horizontalHeaderItems.count(); + return parent.isValid() ? 0 : horizontalHeaderItems.size(); } QVariant QTableModel::data(const QModelIndex &index, int role) const @@ -400,7 +400,7 @@ QMap<int, QVariant> QTableModel::itemData(const QModelIndex &index) const QMap<int, QVariant> roles; QTableWidgetItem *itm = item(index); if (itm) { - for (int i = 0; i < itm->values.count(); ++i) { + for (int i = 0; i < itm->values.size(); ++i) { roles.insert(itm->values.at(i).role, itm->values.at(i).value); } @@ -492,7 +492,7 @@ void QTableModel::sort(int column, Qt::SortOrder order) const auto compare = (order == Qt::AscendingOrder ? &itemLessThan : &itemGreaterThan); std::stable_sort(sortable.begin(), sortable.end(), compare); - QList<QTableWidgetItem *> sorted_table(tableItems.count()); + QList<QTableWidgetItem *> sorted_table(tableItems.size()); QModelIndexList from; QModelIndexList to; const int numRows = rowCount(); @@ -500,9 +500,9 @@ void QTableModel::sort(int column, Qt::SortOrder order) from.reserve(numRows * numColumns); to.reserve(numRows * numColumns); for (int i = 0; i < numRows; ++i) { - int r = (i < sortable.count() + int r = (i < sortable.size() ? sortable.at(i).second - : unsortable.at(i - sortable.count())); + : unsortable.at(i - sortable.size())); for (int c = 0; c < numColumns; ++c) { sorted_table[tableIndex(i, c)] = item(r, c); from.append(createIndex(r, c)); @@ -550,7 +550,7 @@ void QTableModel::ensureSorted(int column, Qt::SortOrder order, QList<QTableWidgetItem *>::iterator vit = colItems.begin(); qsizetype distanceFromBegin = 0; bool changed = false; - for (int i = 0; i < sorting.count(); ++i) { + for (int i = 0; i < sorting.size(); ++i) { distanceFromBegin = std::distance(colItems.begin(), vit); int oldRow = sorting.at(i).second; QTableWidgetItem *item = colItems.at(oldRow); @@ -583,7 +583,7 @@ void QTableModel::ensureSorted(int column, Qt::SortOrder order, // update persistent indexes updateRowIndexes(newPersistentIndexes, oldRow, newRow); // the index of the remaining rows may have changed - for (int j = i + 1; j < sorting.count(); ++j) { + for (int j = i + 1; j < sorting.size(); ++j) { int otherRow = sorting.at(j).second; if (oldRow < otherRow && newRow >= otherRow) --sorting[j].second; @@ -684,9 +684,9 @@ QVariant QTableModel::headerData(int section, Qt::Orientation orientation, int r return QVariant(); QTableWidgetItem *itm = nullptr; - if (orientation == Qt::Horizontal && section < horizontalHeaderItems.count()) + if (orientation == Qt::Horizontal && section < horizontalHeaderItems.size()) itm = horizontalHeaderItems.at(section); - else if (orientation == Qt::Vertical && section < verticalHeaderItems.count()) + else if (orientation == Qt::Vertical && section < verticalHeaderItems.size()) itm = verticalHeaderItems.at(section); else return QVariant(); // section is out of bounds @@ -721,20 +721,20 @@ bool QTableModel::setHeaderData(int section, Qt::Orientation orientation, bool QTableModel::isValid(const QModelIndex &index) const { return (index.isValid() - && index.row() < verticalHeaderItems.count() - && index.column() < horizontalHeaderItems.count()); + && index.row() < verticalHeaderItems.size() + && index.column() < horizontalHeaderItems.size()); } void QTableModel::clear() { - for (int j = 0; j < verticalHeaderItems.count(); ++j) { + for (int j = 0; j < verticalHeaderItems.size(); ++j) { if (verticalHeaderItems.at(j)) { verticalHeaderItems.at(j)->view = nullptr; delete verticalHeaderItems.at(j); verticalHeaderItems[j] = 0; } } - for (int k = 0; k < horizontalHeaderItems.count(); ++k) { + for (int k = 0; k < horizontalHeaderItems.size(); ++k) { if (horizontalHeaderItems.at(k)) { horizontalHeaderItems.at(k)->view = nullptr; delete horizontalHeaderItems.at(k); @@ -747,7 +747,7 @@ void QTableModel::clear() void QTableModel::clearContents() { beginResetModel(); - for (int i = 0; i < tableItems.count(); ++i) { + for (int i = 0; i < tableItems.size(); ++i) { if (tableItems.at(i)) { tableItems.at(i)->view = nullptr; delete tableItems.at(i); @@ -809,7 +809,7 @@ QMimeData *QTableModel::internalMimeData() const QMimeData *QTableModel::mimeData(const QModelIndexList &indexes) const { QList<QTableWidgetItem*> items; - const int indexesCount = indexes.count(); + const int indexesCount = indexes.size(); items.reserve(indexesCount); for (int i = 0; i < indexesCount; ++i) items << item(indexes.at(i)); @@ -1380,7 +1380,7 @@ void QTableWidgetItem::setData(int role, const QVariant &value) { bool found = false; role = (role == Qt::EditRole ? Qt::DisplayRole : role); - for (int i = 0; i < values.count(); ++i) { + for (int i = 0; i < values.size(); ++i) { if (values.at(i).role == role) { if (values[i].value == value) return; @@ -2087,7 +2087,7 @@ void QTableWidget::setVerticalHeaderLabels(const QStringList &labels) Q_D(QTableWidget); QTableModel *model = d->tableModel(); QTableWidgetItem *item = nullptr; - for (int i = 0; i < model->rowCount() && i < labels.count(); ++i) { + for (int i = 0; i < model->rowCount() && i < labels.size(); ++i) { item = model->verticalHeaderItem(i); if (!item) { item = model->createItem(); @@ -2105,7 +2105,7 @@ void QTableWidget::setHorizontalHeaderLabels(const QStringList &labels) Q_D(QTableWidget); QTableModel *model = d->tableModel(); QTableWidgetItem *item = nullptr; - for (int i = 0; i < model->columnCount() && i < labels.count(); ++i) { + for (int i = 0; i < model->columnCount() && i < labels.size(); ++i) { item = model->horizontalHeaderItem(i); if (!item) { item = model->createItem(); @@ -2344,7 +2344,7 @@ QList<QTableWidgetSelectionRange> QTableWidget::selectedRanges() const { const QList<QItemSelectionRange> ranges = selectionModel()->selection(); QList<QTableWidgetSelectionRange> result; - const int rangesCount = ranges.count(); + const int rangesCount = ranges.size(); result.reserve(rangesCount); for (int i = 0; i < rangesCount; ++i) result.append({ranges.at(i).top(), @@ -2582,7 +2582,7 @@ QMimeData *QTableWidget::mimeData(const QList<QTableWidgetItem *> &items) const // if non empty, it's called from the model's own mimeData if (cachedIndexes.isEmpty()) { - cachedIndexes.reserve(items.count()); + cachedIndexes.reserve(items.size()); for (QTableWidgetItem *item : items) cachedIndexes << indexFromItem(item); @@ -2697,7 +2697,7 @@ void QTableWidget::dropEvent(QDropEvent *event) { } QList<QTableWidgetItem *> taken; - const int indexesCount = indexes.count(); + const int indexesCount = indexes.size(); taken.reserve(indexesCount); for (const auto &index : indexes) taken.append(takeItem(index.row(), index.column())); diff --git a/src/widgets/itemviews/qtablewidget_p.h b/src/widgets/itemviews/qtablewidget_p.h index 2c4193c0de..1d893224c0 100644 --- a/src/widgets/itemviews/qtablewidget_p.h +++ b/src/widgets/itemviews/qtablewidget_p.h @@ -118,7 +118,7 @@ public: bool isValid(const QModelIndex &index) const; inline long tableIndex(int row, int column) const - { return (row * horizontalHeaderItems.count()) + column; } + { return (row * horizontalHeaderItems.size()) + column; } void clear(); void clearContents(); diff --git a/src/widgets/itemviews/qtreeview.cpp b/src/widgets/itemviews/qtreeview.cpp index 3711a933f6..065c42d6b7 100644 --- a/src/widgets/itemviews/qtreeview.cpp +++ b/src/widgets/itemviews/qtreeview.cpp @@ -1002,9 +1002,9 @@ void QTreeView::keyboardSearch(const QString &search) // special case for searches with same key like 'aaaaa' bool sameKey = false; - if (d->keyboardInput.length() > 1) { - int c = d->keyboardInput.count(d->keyboardInput.at(d->keyboardInput.length() - 1)); - sameKey = (c == d->keyboardInput.length()); + if (d->keyboardInput.size() > 1) { + int c = d->keyboardInput.count(d->keyboardInput.at(d->keyboardInput.size() - 1)); + sameKey = (c == d->keyboardInput.size()); if (sameKey) skipRow = true; } @@ -1029,7 +1029,7 @@ void QTreeView::keyboardSearch(const QString &search) int bestAbove = -1; int bestBelow = -1; QString searchString = sameKey ? QString(d->keyboardInput.at(0)) : d->keyboardInput; - for (int i = 0; i < d->viewItems.count(); ++i) { + for (int i = 0; i < d->viewItems.size(); ++i) { if ((int)d->viewItems.at(i).level > previousLevel) { QModelIndex searchFrom = d->viewItems.at(i).index; if (start.column() > 0) @@ -1037,7 +1037,7 @@ void QTreeView::keyboardSearch(const QString &search) if (searchFrom.parent() == start.parent()) searchFrom = start; QModelIndexList match = d->model->match(searchFrom, Qt::DisplayRole, searchString); - if (match.count()) { + if (match.size()) { int hitIndex = d->viewIndex(match.at(0)); if (hitIndex >= 0 && hitIndex < startIndex) bestAbove = bestAbove == -1 ? hitIndex : qMin(hitIndex, bestAbove); @@ -1458,7 +1458,7 @@ void QTreeView::drawTree(QPainter *painter, const QRegion ®ion) const const QStyle::State state = option.state; d->current = 0; - if (viewItems.count() == 0 || d->header->count() == 0 || !d->itemDelegate) { + if (viewItems.size() == 0 || d->header->count() == 0 || !d->itemDelegate) { d->paintAlternatingRowColors(painter, &option, 0, region.boundingRect().bottom()+1); return; } @@ -1487,7 +1487,7 @@ void QTreeView::drawTree(QPainter *painter, const QRegion ®ion) const int y = firstVisibleItemOffset; // we may only see part of the first item // start at the top of the viewport and iterate down to the update area - for (; i < viewItems.count(); ++i) { + for (; i < viewItems.size(); ++i) { const int itemHeight = d->itemHeight(i); if (y + itemHeight > area.top()) break; @@ -1495,7 +1495,7 @@ void QTreeView::drawTree(QPainter *painter, const QRegion ®ion) const } // paint the visible rows - for (; i < viewItems.count() && y <= area.bottom(); ++i) { + for (; i < viewItems.size() && y <= area.bottom(); ++i) { const int itemHeight = d->itemHeight(i); option.rect.setRect(0, y, viewportWidth, itemHeight); option.state = state | (viewItems.at(i).expanded ? QStyle::State_Open : QStyle::State_None) @@ -1556,11 +1556,11 @@ void QTreeViewPrivate::calcLogicalIndices( } } - itemPositions->resize(logicalIndices->count()); - for (int currentLogicalSection = 0; currentLogicalSection < logicalIndices->count(); ++currentLogicalSection) { + itemPositions->resize(logicalIndices->size()); + for (int currentLogicalSection = 0; currentLogicalSection < logicalIndices->size(); ++currentLogicalSection) { const int headerSection = logicalIndices->at(currentLogicalSection); // determine the viewItemPosition depending on the position of column 0 - int nextLogicalSection = currentLogicalSection + 1 >= logicalIndices->count() + int nextLogicalSection = currentLogicalSection + 1 >= logicalIndices->size() ? logicalIndexAfterRight : logicalIndices->at(currentLogicalSection + 1); int prevLogicalSection = currentLogicalSection - 1 < 0 @@ -1659,8 +1659,11 @@ void QTreeView::drawRow(QPainter *painter, const QStyleOptionViewItem &option, } } - // ### special case: treeviews with multiple columns draw - // the selections differently than with only one column + // ### special case: if we select entire rows, then we need to draw the + // selection in the first column all the way to the second column, rather + // than just around the item text. We abuse showDecorationSelected to + // indicate this to the style. Below we will reset this value temporarily + // to only respect the styleHint while we are rendering the decoration. opt.showDecorationSelected = (d->selectionBehavior & SelectRows) || option.showDecorationSelected; @@ -1676,7 +1679,7 @@ void QTreeView::drawRow(QPainter *painter, const QStyleOptionViewItem &option, viewItemPosList; // vector of left/middle/end for each logicalIndex d->calcLogicalIndices(&logicalIndices, &viewItemPosList, left, right); - for (int currentLogicalSection = 0; currentLogicalSection < logicalIndices.count(); ++currentLogicalSection) { + for (int currentLogicalSection = 0; currentLogicalSection < logicalIndices.size(); ++currentLogicalSection) { int headerSection = logicalIndices.at(currentLogicalSection); position = columnViewportPosition(headerSection) + offset.x(); width = header->sectionSize(headerSection); @@ -1745,8 +1748,16 @@ void QTreeView::drawRow(QPainter *painter, const QStyleOptionViewItem &option, } // draw background for the branch (selection + alternate row) opt.rect = branches; - if (style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, &opt, this)) - style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &opt, painter, this); + + // We use showDecorationSelected both to store the style hint, and to indicate + // that the entire row has to be selected (see overrides of the value if + // selectionBehavior == SelectRow). + // While we are only painting the background we don't care for the + // selectionBehavior factor, so respect only the style value, and reset later. + const bool oldShowDecorationSelected = opt.showDecorationSelected; + opt.showDecorationSelected = style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, + &opt, this); + style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &opt, painter, this); // draw background of the item (only alternate row). rest of the background // is provided by the delegate @@ -1755,6 +1766,7 @@ void QTreeView::drawRow(QPainter *painter, const QStyleOptionViewItem &option, opt.rect.setRect(reverse ? position : i + position, y, width - i, height); style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &opt, painter, this); opt.state = oldState; + opt.showDecorationSelected = oldShowDecorationSelected; if (d->indent != 0) drawBranches(painter, branches, index); @@ -1961,13 +1973,13 @@ void QTreeView::mouseDoubleClickEvent(QMouseEvent *event) if (d->itemsExpandable && d->expandsOnDoubleClick && d->hasVisibleChildren(persistent)) { - if (!((i < d->viewItems.count()) && (d->viewItems.at(i).index == firstColumnIndex))) { + if (!((i < d->viewItems.size()) && (d->viewItems.at(i).index == firstColumnIndex))) { // find the new index of the item - for (i = 0; i < d->viewItems.count(); ++i) { + for (i = 0; i < d->viewItems.size(); ++i) { if (d->viewItems.at(i).index == firstColumnIndex) break; } - if (i == d->viewItems.count()) + if (i == d->viewItems.size()) return; } if (d->viewItems.at(i).expanded) @@ -2065,7 +2077,7 @@ QModelIndex QTreeView::indexBelow(const QModelIndex &index) const return QModelIndex(); d->executePostedLayout(); int i = d->viewIndex(index); - if (++i >= d->viewItems.count()) + if (++i >= d->viewItems.size()) return QModelIndex(); const QModelIndex firstColumnIndex = d->viewItems.at(i).index; return firstColumnIndex.sibling(firstColumnIndex.row(), index.column()); @@ -2149,7 +2161,7 @@ int QTreeView::verticalOffset() const // ### find a faster way to do this d->executePostedLayout(); int offset = 0; - const int cnt = qMin(d->viewItems.count(), verticalScrollBar()->value()); + const int cnt = qMin(d->viewItems.size(), verticalScrollBar()->value()); for (int i = 0; i < cnt; ++i) offset += d->itemHeight(i); return offset; @@ -2175,7 +2187,7 @@ QModelIndex QTreeView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifie int c = 0; while (c < d->header->count() && d->header->isSectionHidden(d->header->logicalIndex(c))) ++c; - if (i < d->viewItems.count() && c < d->header->count()) { + if (i < d->viewItems.size() && c < d->header->count()) { return d->modelIndex(i, d->header->logicalIndex(c)); } return QModelIndex(); @@ -2207,7 +2219,7 @@ QModelIndex QTreeView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifie return d->modelIndex(d->above(vi), current.column()); case MoveLeft: { QScrollBar *sb = horizontalScrollBar(); - if (vi < d->viewItems.count() && d->viewItems.at(vi).expanded && d->itemsExpandable && sb->value() == sb->minimum()) { + if (vi < d->viewItems.size() && d->viewItems.at(vi).expanded && d->itemsExpandable && sb->value() == sb->minimum()) { d->collapse(vi, true); d->moveCursorUpdatedView = true; } else { @@ -2242,7 +2254,7 @@ QModelIndex QTreeView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifie break; } case MoveRight: - if (vi < d->viewItems.count() && !d->viewItems.at(vi).expanded && d->itemsExpandable + if (vi < d->viewItems.size() && !d->viewItems.at(vi).expanded && d->itemsExpandable && d->hasVisibleChildren(d->viewItems.at(vi).index)) { d->expand(vi, true); d->moveCursorUpdatedView = true; @@ -2397,7 +2409,7 @@ QModelIndexList QTreeView::selectedIndexes() const QModelIndexList modelSelected; if (selectionModel()) modelSelected = selectionModel()->selectedIndexes(); - for (int i = 0; i < modelSelected.count(); ++i) { + for (int i = 0; i < modelSelected.size(); ++i) { // check that neither the parents nor the index is hidden before we add QModelIndex index = modelSelected.at(i); while (index.isValid() && !isIndexHidden(index)) @@ -2434,7 +2446,7 @@ void QTreeView::scrollContentsBy(int dx, int dy) // guestimate the number of items in the viewport int viewCount = d->viewport->height() / itemHeight; - int maxDeltaY = qMin(d->viewItems.count(), viewCount); + int maxDeltaY = qMin(d->viewItems.size(), viewCount); // no need to do a lot of work if we are going to redraw the whole thing anyway if (qAbs(dy) > qAbs(maxDeltaY) && d->editorIndexHash.isEmpty()) { verticalScrollBar()->update(); @@ -2450,12 +2462,12 @@ void QTreeView::scrollContentsBy(int dx, int dy) dy = 0; if (previousViewIndex < currentViewIndex) { // scrolling down for (int i = previousViewIndex; i < currentViewIndex; ++i) { - if (i < d->viewItems.count()) + if (i < d->viewItems.size()) dy -= d->itemHeight(i); } } else if (previousViewIndex > currentViewIndex) { // scrolling up for (int i = previousViewIndex - 1; i >= currentViewIndex; --i) { - if (i < d->viewItems.count()) + if (i < d->viewItems.size()) dy += d->itemHeight(i); } } @@ -2758,7 +2770,7 @@ void QTreeView::expandToDepth(int depth) d->expandedIndexes.clear(); d->interruptDelayedItemsLayout(); d->layout(-1); - for (int i = 0; i < d->viewItems.count(); ++i) { + for (int i = 0; i < d->viewItems.size(); ++i) { if (d->viewItems.at(i).level <= (uint)depth) { d->viewItems[i].expanded = true; d->layout(i); @@ -3092,7 +3104,7 @@ void QTreeViewPrivate::insertViewItems(int pos, int count, const QTreeViewItem & { viewItems.insert(pos, count, viewItem); QTreeViewItem *items = viewItems.data(); - for (int i = pos + count; i < viewItems.count(); i++) + for (int i = pos + count; i < viewItems.size(); i++) if (items[i].parentItem >= pos) items[i].parentItem += count; } @@ -3101,7 +3113,7 @@ void QTreeViewPrivate::removeViewItems(int pos, int count) { viewItems.remove(pos, count); QTreeViewItem *items = viewItems.data(); - for (int i = pos; i < viewItems.count(); i++) + for (int i = pos; i < viewItems.size(); i++) if (items[i].parentItem >= pos) items[i].parentItem -= count; } @@ -3345,7 +3357,7 @@ void QTreeViewPrivate::layout(int i, bool recursiveExpanding, bool afterIsUninit if (!afterIsUninitialized) insertViewItems(i + 1, count, QTreeViewItem()); // expand else if (count > 0) - viewItems.resize(viewItems.count() + count); + viewItems.resize(viewItems.size() + count); } else { expanding = false; } @@ -3415,7 +3427,7 @@ int QTreeViewPrivate::pageUp(int i) const index = 0; while (isItemHiddenOrDisabled(index)) index++; - return index >= viewItems.count() ? 0 : index; + return index >= viewItems.size() ? 0 : index; } int QTreeViewPrivate::pageDown(int i) const @@ -3423,11 +3435,11 @@ int QTreeViewPrivate::pageDown(int i) const int index = itemAtCoordinate(coordinateForItem(i) + viewport->height()); while (isItemHiddenOrDisabled(index)) index++; - if (index == -1 || index >= viewItems.count()) - index = viewItems.count() - 1; + if (index == -1 || index >= viewItems.size()) + index = viewItems.size() - 1; while (isItemHiddenOrDisabled(index)) index--; - return index == -1 ? viewItems.count() - 1 : index; + return index == -1 ? viewItems.size() - 1 : index; } int QTreeViewPrivate::itemForKeyHome() const @@ -3435,20 +3447,20 @@ int QTreeViewPrivate::itemForKeyHome() const int index = 0; while (isItemHiddenOrDisabled(index)) index++; - return index >= viewItems.count() ? 0 : index; + return index >= viewItems.size() ? 0 : index; } int QTreeViewPrivate::itemForKeyEnd() const { - int index = viewItems.count() - 1; + int index = viewItems.size() - 1; while (isItemHiddenOrDisabled(index)) index--; - return index == -1 ? viewItems.count() - 1 : index; + return index == -1 ? viewItems.size() - 1 : index; } int QTreeViewPrivate::indentationForItem(int item) const { - if (item < 0 || item >= viewItems.count()) + if (item < 0 || item >= viewItems.size()) return 0; int level = viewItems.at(item).level; if (rootDecoration) @@ -3458,7 +3470,7 @@ int QTreeViewPrivate::indentationForItem(int item) const int QTreeViewPrivate::itemHeight(int item) const { - Q_ASSERT(item < viewItems.count()); + Q_ASSERT(item < viewItems.size()); if (uniformRowHeights) return defaultItemHeight; if (viewItems.isEmpty()) @@ -3486,7 +3498,7 @@ int QTreeViewPrivate::coordinateForItem(int item) const return (item * defaultItemHeight) - vbar->value(); // ### optimize (maybe do like QHeaderView by letting items have startposition) int y = 0; - for (int i = 0; i < viewItems.count(); ++i) { + for (int i = 0; i < viewItems.size(); ++i) { if (i == item) return y - vbar->value(); y += itemHeight(i); @@ -3500,7 +3512,7 @@ int QTreeViewPrivate::coordinateForItem(int item) const // ### slow if the item is not visible int viewItemCoordinate = 0; int viewItemIndex = topViewItemIndex; - while (viewItemIndex < viewItems.count()) { + while (viewItemIndex < viewItems.size()) { if (viewItemIndex == item) return viewItemCoordinate; viewItemCoordinate += itemHeight(viewItemIndex); @@ -3532,7 +3544,7 @@ int QTreeViewPrivate::coordinateForItem(int item) const */ int QTreeViewPrivate::itemAtCoordinate(int coordinate) const { - const int itemCount = viewItems.count(); + const int itemCount = viewItems.size(); if (itemCount == 0) return -1; if (uniformRowHeights && defaultItemHeight <= 0) @@ -3545,7 +3557,7 @@ int QTreeViewPrivate::itemAtCoordinate(int coordinate) const // ### optimize int viewItemCoordinate = 0; const int contentsCoordinate = coordinate + vbar->value(); - for (int viewItemIndex = 0; viewItemIndex < viewItems.count(); ++viewItemIndex) { + for (int viewItemIndex = 0; viewItemIndex < viewItems.size(); ++viewItemIndex) { viewItemCoordinate += itemHeight(viewItemIndex); if (viewItemCoordinate > contentsCoordinate) return (viewItemIndex >= itemCount ? -1 : viewItemIndex); @@ -3561,7 +3573,7 @@ int QTreeViewPrivate::itemAtCoordinate(int coordinate) const if (coordinate >= 0) { // the coordinate is in or below the viewport int viewItemCoordinate = 0; - for (int viewItemIndex = topViewItemIndex; viewItemIndex < viewItems.count(); ++viewItemIndex) { + for (int viewItemIndex = topViewItemIndex; viewItemIndex < viewItems.size(); ++viewItemIndex) { viewItemCoordinate += itemHeight(viewItemIndex); if (viewItemCoordinate > coordinate) return (viewItemIndex >= itemCount ? -1 : viewItemIndex); @@ -3584,7 +3596,7 @@ int QTreeViewPrivate::viewIndex(const QModelIndex &_index) const if (!_index.isValid() || viewItems.isEmpty()) return -1; - const int totalCount = viewItems.count(); + const int totalCount = viewItems.size(); const QModelIndex index = _index.sibling(_index.row(), 0); const int row = index.row(); const quintptr internalId = index.internalId(); @@ -3625,7 +3637,7 @@ int QTreeViewPrivate::viewIndex(const QModelIndex &_index) const QModelIndex QTreeViewPrivate::modelIndex(int i, int column) const { - if (i < 0 || i >= viewItems.count()) + if (i < 0 || i >= viewItems.size()) return QModelIndex(); QModelIndex ret = viewItems.at(i).index; @@ -3640,7 +3652,7 @@ int QTreeViewPrivate::firstVisibleItem(int *offset) const if (verticalScrollMode == QAbstractItemView::ScrollPerItem) { if (offset) *offset = 0; - return (value < 0 || value >= viewItems.count()) ? -1 : value; + return (value < 0 || value >= viewItems.size()) ? -1 : value; } // ScrollMode == ScrollPerPixel if (uniformRowHeights) { @@ -3652,7 +3664,7 @@ int QTreeViewPrivate::firstVisibleItem(int *offset) const return value / defaultItemHeight; } int y = 0; // ### (maybe do like QHeaderView by letting items have startposition) - for (int i = 0; i < viewItems.count(); ++i) { + for (int i = 0; i < viewItems.size(); ++i) { y += itemHeight(i); // the height value is cached if (y > value) { if (offset) @@ -3673,7 +3685,7 @@ int QTreeViewPrivate::lastVisibleItem(int firstVisual, int offset) const int y = - offset; int value = viewport->height(); - for (int i = firstVisual; i < viewItems.count(); ++i) { + for (int i = firstVisual; i < viewItems.size(); ++i) { y += itemHeight(i); // the height value is cached if (y > value) return i; @@ -3701,11 +3713,11 @@ void QTreeViewPrivate::updateScrollBars() int itemsInViewport = 0; if (uniformRowHeights) { if (defaultItemHeight <= 0) - itemsInViewport = viewItems.count(); + itemsInViewport = viewItems.size(); else itemsInViewport = viewportSize.height() / defaultItemHeight; } else { - const int itemsCount = viewItems.count(); + const int itemsCount = viewItems.size(); const int viewportHeight = viewportSize.height(); for (int height = 0, item = itemsCount - 1; item >= 0; --item) { height += itemHeight(item); @@ -3717,15 +3729,15 @@ void QTreeViewPrivate::updateScrollBars() if (verticalScrollMode == QAbstractItemView::ScrollPerItem) { if (!viewItems.isEmpty()) itemsInViewport = qMax(1, itemsInViewport); - vbar->setRange(0, viewItems.count() - itemsInViewport); + vbar->setRange(0, viewItems.size() - itemsInViewport); vbar->setPageStep(itemsInViewport); vbar->setSingleStep(1); } else { // scroll per pixel int contentsHeight = 0; if (uniformRowHeights) { - contentsHeight = defaultItemHeight * viewItems.count(); + contentsHeight = defaultItemHeight * viewItems.size(); } else { // ### (maybe do like QHeaderView by letting items have startposition) - for (int i = 0; i < viewItems.count(); ++i) + for (int i = 0; i < viewItems.size(); ++i) contentsHeight += itemHeight(i); } vbar->setRange(0, contentsHeight - viewportSize.height()); @@ -3834,7 +3846,7 @@ QList<QPair<int, int>> QTreeViewPrivate::columnRanges(const QModelIndex &topInde QPair<int, int> current; current.first = -2; // -1 is not enough because -1+1 = 0 current.second = -2; - for(int i = 0; i < logicalIndexes.count(); ++i) { + for(int i = 0; i < logicalIndexes.size(); ++i) { const int logicalColumn = logicalIndexes.at(i); if (current.second + 1 != logicalColumn) { if (current.first != -2) { @@ -3910,7 +3922,7 @@ void QTreeViewPrivate::select(const QModelIndex &topIndex, const QModelIndex &bo } if (currentRange.isValid()) selection.append(currentRange); - for (int i = 0; i < rangeStack.count(); ++i) + for (int i = 0; i < rangeStack.size(); ++i) selection.append(rangeStack.at(i)); } q->selectionModel()->select(selection, command); diff --git a/src/widgets/itemviews/qtreeview_p.h b/src/widgets/itemviews/qtreeview_p.h index 9449f5f5e9..22f6eaec22 100644 --- a/src/widgets/itemviews/qtreeview_p.h +++ b/src/widgets/itemviews/qtreeview_p.h @@ -196,7 +196,7 @@ public: } inline bool isItemHiddenOrDisabled(int i) const { - if (i < 0 || i >= viewItems.count()) + if (i < 0 || i >= viewItems.size()) return false; const QModelIndex index = viewItems.at(i).index; return isRowHidden(index) || !isIndexEnabled(index); @@ -205,7 +205,7 @@ public: inline int above(int item) const { int i = item; while (isItemHiddenOrDisabled(--item)){} return item < 0 ? i : item; } inline int below(int item) const - { int i = item; while (isItemHiddenOrDisabled(++item)){} return item >= viewItems.count() ? i : item; } + { int i = item; while (isItemHiddenOrDisabled(++item)){} return item >= viewItems.size() ? i : item; } inline void invalidateHeightCache(int item) const { viewItems[item].height = 0; } diff --git a/src/widgets/itemviews/qtreewidget.cpp b/src/widgets/itemviews/qtreewidget.cpp index 6df5dffb90..3fa8a7e1b9 100644 --- a/src/widgets/itemviews/qtreewidget.cpp +++ b/src/widgets/itemviews/qtreewidget.cpp @@ -204,7 +204,7 @@ QModelIndex QTreeModel::index(const QTreeWidgetItem *item, int column) const int row; int guess = item->d->rowGuess; if (guess >= 0 - && par->children.count() > guess + && par->children.size() > guess && par->children.at(guess) == itm) { row = guess; } else { @@ -381,8 +381,8 @@ QMap<int, QVariant> QTreeModel::itemData(const QModelIndex &index) const QTreeWidgetItem *itm = item(index); if (itm) { int column = index.column(); - if (column < itm->values.count()) { - for (int i = 0; i < itm->values.at(column).count(); ++i) { + if (column < itm->values.size()) { + for (int i = 0; i < itm->values.at(column).size(); ++i) { roles.insert(itm->values.at(column).at(i).role, itm->values.at(column).at(i).value); } @@ -451,9 +451,9 @@ bool QTreeModel::insertColumns(int column, int count, const QModelIndex &parent) while (!itemstack.isEmpty()) { QTreeWidgetItem *par = itemstack.pop(); QList<QTreeWidgetItem*> children = par ? par->children : rootItem->children; - for (int row = 0; row < children.count(); ++row) { + for (int row = 0; row < children.size(); ++row) { QTreeWidgetItem *child = children.at(row); - if (child->children.count()) + if (child->children.size()) itemstack.push(child); child->values.insert(column, count, QList<QWidgetItemData>()); } @@ -627,7 +627,7 @@ void QTreeModel::ensureSorted(int column, Qt::SortOrder order, else if (oldRow > otherRow && newRow <= otherRow) ++sorting[j].second; } - for (int k = 0; k < newPersistentIndexes.count(); ++k) { + for (int k = 0; k < newPersistentIndexes.size(); ++k) { QModelIndex pi = newPersistentIndexes.at(k); if (pi.parent() != parent) continue; @@ -806,7 +806,7 @@ void QTreeModel::beginRemoveItems(QTreeWidgetItem *parent, int row, int count) if (!parent) parent = rootItem; // now update the iterators - for (int i = 0; i < iterators.count(); ++i) { + for (int i = 0; i < iterators.size(); ++i) { for (int j = 0; j < count; j++) { QTreeWidgetItem *c = parent->child(row + j); iterators[i]->d_func()->ensureValidIterator(c); @@ -827,8 +827,8 @@ void QTreeModel::sortItems(QList<QTreeWidgetItem*> *items, int column, Qt::SortO return; // store the original order of indexes - QList<QPair<QTreeWidgetItem *, int>> sorting(items->count()); - for (int i = 0; i < sorting.count(); ++i) { + QList<QPair<QTreeWidgetItem *, int>> sorting(items->size()); + for (int i = 0; i < sorting.size(); ++i) { sorting[i].first = items->at(i); sorting[i].second = i; } @@ -840,7 +840,7 @@ void QTreeModel::sortItems(QList<QTreeWidgetItem*> *items, int column, Qt::SortO QModelIndexList fromList; QModelIndexList toList; int colCount = columnCount(); - for (int r = 0; r < sorting.count(); ++r) { + for (int r = 0; r < sorting.size(); ++r) { int oldRow = sorting.at(r).second; if (oldRow == r) continue; @@ -1396,7 +1396,7 @@ QTreeWidgetItem::QTreeWidgetItem(int type) : rtti(type), d(new QTreeWidgetItemPr QTreeWidgetItem::QTreeWidgetItem(const QStringList &strings, int type) : rtti(type), d(new QTreeWidgetItemPrivate(this)) { - for (int i = 0; i < strings.count(); ++i) + for (int i = 0; i < strings.size(); ++i) setText(i, strings.at(i)); } @@ -1432,7 +1432,7 @@ QTreeWidgetItem::QTreeWidgetItem(QTreeWidget *treeview, int type) QTreeWidgetItem::QTreeWidgetItem(QTreeWidget *treeview, const QStringList &strings, int type) : rtti(type), d(new QTreeWidgetItemPrivate(this)) { - for (int i = 0; i < strings.count(); ++i) + for (int i = 0; i < strings.size(); ++i) setText(i, strings.at(i)); // do not set this->view here otherwise insertChild() will fail if (QTreeModel *model = treeModel(treeview)) { @@ -1481,7 +1481,7 @@ QTreeWidgetItem::QTreeWidgetItem(QTreeWidgetItem *parent, int type) QTreeWidgetItem::QTreeWidgetItem(QTreeWidgetItem *parent, const QStringList &strings, int type) : rtti(type), d(new QTreeWidgetItemPrivate(this)) { - for (int i = 0; i < strings.count(); ++i) + for (int i = 0; i < strings.size(); ++i) setText(i, strings.at(i)); if (parent) parent->addChild(this); @@ -1544,7 +1544,7 @@ QTreeWidgetItem::~QTreeWidgetItem() } // at this point the persistent indexes for the children should also be invalidated // since we invalidated the parent - for (int i = 0; i < children.count(); ++i) { + for (int i = 0; i < children.size(); ++i) { QTreeWidgetItem *child = children.at(i); // make sure the child does not try to remove itself from our children list child->par = nullptr; @@ -1652,7 +1652,7 @@ void QTreeWidgetItem::setFlags(Qt::ItemFlags flags) parents.push(this); while (!parents.isEmpty()) { QTreeWidgetItem *parent = parents.pop(); - for (int i = 0; i < parent->children.count(); ++i) { + for (int i = 0; i < parent->children.size(); ++i) { QTreeWidgetItem *child = parent->children.at(i); if (!child->d->disabled) { // if not explicitly disabled parents.push(child); @@ -1681,7 +1681,7 @@ void QTreeWidgetItemPrivate::updateHiddenStatus(QTreeWidgetItem *item, bool inse const QModelIndex index = model->index(parent, 0); item->view->setRowHidden(index.row(), index.parent(), inserting); } - for (int i = 0; i < parent->children.count(); ++i) { + for (int i = 0; i < parent->children.size(); ++i) { QTreeWidgetItem *child = parent->children.at(i); parents.push(child); } @@ -1707,7 +1707,7 @@ void QTreeWidgetItemPrivate::propagateDisabled(QTreeWidgetItem *item) parent->itemChanged(); } - for (int i = 0; i < parent->children.count(); ++i) { + for (int i = 0; i < parent->children.size(); ++i) { QTreeWidgetItem *child = parent->children.at(i); parents.push(child); } @@ -1749,14 +1749,14 @@ void QTreeWidgetItem::setData(int column, int role, const QVariant &value) switch (role) { case Qt::EditRole: case Qt::DisplayRole: { - if (values.count() <= column) { + if (values.size() <= column) { if (model && this == model->headerItem) model->setColumnCount(column + 1); else values.resize(column + 1); } - if (d->display.count() <= column) { - for (int i = d->display.count() - 1; i < column - 1; ++i) + if (d->display.size() <= column) { + for (int i = d->display.size() - 1; i < column - 1; ++i) d->display.append(QVariant()); d->display.append(value); } else if (d->display[column] != value) { @@ -1767,7 +1767,7 @@ void QTreeWidgetItem::setData(int column, int role, const QVariant &value) } break; case Qt::CheckStateRole: if ((itemFlags & Qt::ItemIsAutoTristate) && value != Qt::PartiallyChecked) { - for (int i = 0; i < children.count(); ++i) { + for (int i = 0; i < children.size(); ++i) { QTreeWidgetItem *child = children.at(i); if (child->data(column, role).isValid()) {// has a CheckState Qt::ItemFlags f = itemFlags; // a little hack to avoid multiple dataChanged signals @@ -1779,10 +1779,10 @@ void QTreeWidgetItem::setData(int column, int role, const QVariant &value) } Q_FALLTHROUGH(); default: - if (column < values.count()) { + if (column < values.size()) { bool found = false; const QList<QWidgetItemData> column_values = values.at(column); - for (int i = 0; i < column_values.count(); ++i) { + for (int i = 0; i < column_values.size(); ++i) { if (column_values.at(i).role == role) { if (column_values.at(i).value == value) return; // value is unchanged @@ -1823,12 +1823,12 @@ QVariant QTreeWidgetItem::data(int column, int role) const switch (role) { case Qt::EditRole: case Qt::DisplayRole: - if (column >= 0 && column < d->display.count()) + if (column >= 0 && column < d->display.size()) return d->display.at(column); break; case Qt::CheckStateRole: // special case for check state in tristate - if (children.count() && (itemFlags & Qt::ItemIsAutoTristate)) + if (children.size() && (itemFlags & Qt::ItemIsAutoTristate)) return childrenCheckState(column); Q_FALLTHROUGH(); default: @@ -1870,9 +1870,9 @@ void QTreeWidgetItem::read(QDataStream &in) d->display.clear(); in >> values; // move the display value over to the display string list - for (int column = 0; column < values.count(); ++column) { + for (int column = 0; column < values.size(); ++column) { d->display << QVariant(); - for (int i = 0; i < values.at(column).count(); ++i) { + for (int i = 0; i < values.at(column).size(); ++i) { if (values.at(column).at(i).role == Qt::DisplayRole) { d->display[column] = values.at(column).at(i).value; values[column].remove(i--); @@ -1939,8 +1939,8 @@ QTreeWidgetItem &QTreeWidgetItem::operator=(const QTreeWidgetItem &other) void QTreeWidgetItem::addChild(QTreeWidgetItem *child) { if (child) { - insertChild(children.count(), child); - child->d->rowGuess = children.count() - 1; + insertChild(children.size(), child); + child->d->rowGuess = children.size() - 1; } } @@ -1951,7 +1951,7 @@ void QTreeWidgetItem::addChild(QTreeWidgetItem *child) */ void QTreeWidgetItem::insertChild(int index, QTreeWidgetItem *child) { - if (index < 0 || index > children.count() || child == nullptr || child->view != nullptr || child->par != nullptr) + if (index < 0 || index > children.size() || child == nullptr || child->view != nullptr || child->par != nullptr) return; if (QTreeModel *model = treeModel()) { @@ -1973,7 +1973,7 @@ void QTreeWidgetItem::insertChild(int index, QTreeWidgetItem *child) QTreeWidgetItem *i = stack.pop(); i->view = view; i->values.reserve(cols); - for (int c = 0; c < i->children.count(); ++c) + for (int c = 0; c < i->children.size(); ++c) stack.push(i->children.at(c)); } children.insert(index, child); @@ -2012,7 +2012,7 @@ QTreeWidgetItem *QTreeWidgetItem::takeChild(int index) model->skipPendingSort = false; model->executePendingSort(); } - if (index >= 0 && index < children.count()) { + if (index >= 0 && index < children.size()) { if (model) model->beginRemoveItems(this, index, 1); d->updateHiddenStatus(children.at(index), false); QTreeWidgetItem *item = children.takeAt(index); @@ -2022,7 +2022,7 @@ QTreeWidgetItem *QTreeWidgetItem::takeChild(int index) while (!stack.isEmpty()) { QTreeWidgetItem *i = stack.pop(); i->view = nullptr; - for (int c = 0; c < i->children.count(); ++c) + for (int c = 0; c < i->children.size(); ++c) stack.push(i->children.at(c)); } d->propagateDisabled(item); @@ -2041,7 +2041,7 @@ QTreeWidgetItem *QTreeWidgetItem::takeChild(int index) */ void QTreeWidgetItem::addChildren(const QList<QTreeWidgetItem*> &children) { - insertChildren(this->children.count(), children); + insertChildren(this->children.size(), children); } /*! @@ -2053,18 +2053,18 @@ void QTreeWidgetItem::addChildren(const QList<QTreeWidgetItem*> &children) */ void QTreeWidgetItem::insertChildren(int index, const QList<QTreeWidgetItem*> &children) { - if (index < 0 || index > this->children.count() || children.isEmpty()) + if (index < 0 || index > this->children.size() || children.isEmpty()) return; if (view && view->isSortingEnabled()) { - for (int n = 0; n < children.count(); ++n) + for (int n = 0; n < children.size(); ++n) insertChild(index, children.at(n)); return; } QTreeModel *model = treeModel(); QStack<QTreeWidgetItem*> stack; QList<QTreeWidgetItem*> itemsToInsert; - for (int n = 0; n < children.count(); ++n) { + for (int n = 0; n < children.size(); ++n) { QTreeWidgetItem *child = children.at(n); if (child->view || child->par) continue; @@ -2084,11 +2084,11 @@ void QTreeWidgetItem::insertChildren(int index, const QList<QTreeWidgetItem*> &c while (!stack.isEmpty()) { QTreeWidgetItem *i = stack.pop(); i->view = view; - for (int c = 0; c < i->children.count(); ++c) + for (int c = 0; c < i->children.size(); ++c) stack.push(i->children.at(c)); } - if (model) model->beginInsertItems(this, index, itemsToInsert.count()); - for (int n = 0; n < itemsToInsert.count(); ++n) { + if (model) model->beginInsertItems(this, index, itemsToInsert.size()); + for (int n = 0; n < itemsToInsert.size(); ++n) { QTreeWidgetItem *child = itemsToInsert.at(n); this->children.insert(index + n, child); if (child->par) @@ -2107,7 +2107,7 @@ void QTreeWidgetItem::insertChildren(int index, const QList<QTreeWidgetItem*> &c QList<QTreeWidgetItem*> QTreeWidgetItem::takeChildren() { QList<QTreeWidgetItem*> removed; - if (children.count() > 0) { + if (children.size() > 0) { QTreeModel *model = treeModel(); if (model) { // This will trigger a layoutChanged signal, thus we might want to optimize @@ -2116,8 +2116,8 @@ QList<QTreeWidgetItem*> QTreeWidgetItem::takeChildren() // is updated in case we take an item that is selected. model->executePendingSort(); } - if (model) model->beginRemoveItems(this, 0, children.count()); - for (int n = 0; n < children.count(); ++n) { + if (model) model->beginRemoveItems(this, 0, children.size()); + for (int n = 0; n < children.size(); ++n) { QTreeWidgetItem *item = children.at(n); item->par = nullptr; QStack<QTreeWidgetItem*> stack; @@ -2125,7 +2125,7 @@ QList<QTreeWidgetItem*> QTreeWidgetItem::takeChildren() while (!stack.isEmpty()) { QTreeWidgetItem *i = stack.pop(); i->view = nullptr; - for (int c = 0; c < i->children.count(); ++c) + for (int c = 0; c < i->children.size(); ++c) stack.push(i->children.at(c)); } d->propagateDisabled(item); @@ -2375,13 +2375,13 @@ void QTreeWidgetPrivate::_q_selectionChanged(const QItemSelection &selected, con QModelIndexList indices = selected.indexes(); int i; QTreeModel *m = treeModel(); - for (i = 0; i < indices.count(); ++i) { + for (i = 0; i < indices.size(); ++i) { QTreeWidgetItem *item = m->item(indices.at(i)); item->d->selected = true; } indices = deselected.indexes(); - for (i = 0; i < indices.count(); ++i) { + for (i = 0; i < indices.size(); ++i) { QTreeWidgetItem *item = m->item(indices.at(i)); item->d->selected = false; } @@ -2806,10 +2806,10 @@ void QTreeWidget::setHeaderItem(QTreeWidgetItem *item) void QTreeWidget::setHeaderLabels(const QStringList &labels) { Q_D(QTreeWidget); - if (columnCount() < labels.count()) - setColumnCount(labels.count()); + if (columnCount() < labels.size()) + setColumnCount(labels.size()); QTreeWidgetItem *item = d->treeModel()->headerItem; - for (int i = 0; i < labels.count(); ++i) + for (int i = 0; i < labels.size(); ++i) item->setText(i, labels.at(i)); } @@ -3052,8 +3052,8 @@ QList<QTreeWidgetItem*> QTreeWidget::selectedItems() const Q_D(const QTreeWidget); const QModelIndexList indexes = selectionModel()->selectedIndexes(); QList<QTreeWidgetItem*> items; - items.reserve(indexes.count()); - QDuplicateTracker<QTreeWidgetItem *> seen(indexes.count()); + items.reserve(indexes.size()); + QDuplicateTracker<QTreeWidgetItem *> seen(indexes.size()); for (const auto &index : indexes) { QTreeWidgetItem *item = d->item(index); if (item->isHidden() || seen.hasSeen(item)) @@ -3206,7 +3206,7 @@ QMimeData *QTreeWidget::mimeData(const QList<QTreeWidgetItem *> &items) const return nullptr; } - for (int c = 0; c < item->values.count(); ++c) { + for (int c = 0; c < item->values.size(); ++c) { const QModelIndex index = indexFromItem(item, c); if (Q_UNLIKELY(!index.isValid())) { qWarning() << "QTreeWidget::mimeData: No index associated with item :" << item; @@ -3285,7 +3285,7 @@ void QTreeWidget::dropEvent(QDropEvent *event) { if (!event->isAccepted() && d->dropOn(event, &row, &col, &topIndex)) { const QList<QModelIndex> idxs = selectedIndexes(); QList<QPersistentModelIndex> indexes; - const int indexesCount = idxs.count(); + const int indexesCount = idxs.size(); indexes.reserve(indexesCount); for (const auto &idx : idxs) indexes.append(idx); @@ -3308,7 +3308,7 @@ void QTreeWidget::dropEvent(QDropEvent *event) { } // insert them back in at their new positions - for (int i = 0; i < indexes.count(); ++i) { + for (int i = 0; i < indexes.size(); ++i) { // Either at a specific point or appended if (row == -1) { if (topIndex.isValid()) { diff --git a/src/widgets/itemviews/qtreewidget.h b/src/widgets/itemviews/qtreewidget.h index 99f31ee421..fec9d82f60 100644 --- a/src/widgets/itemviews/qtreewidget.h +++ b/src/widgets/itemviews/qtreewidget.h @@ -148,8 +148,8 @@ public: executePendingSort(); return children.at(index); } - inline int childCount() const { return children.count(); } - inline int columnCount() const { return values.count(); } + inline int childCount() const { return children.size(); } + inline int columnCount() const { return values.size(); } inline int indexOfChild(QTreeWidgetItem *child) const; void addChild(QTreeWidgetItem *child); diff --git a/src/widgets/kernel/qapplication.cpp b/src/widgets/kernel/qapplication.cpp index f7819471b6..d40c544f8b 100644 --- a/src/widgets/kernel/qapplication.cpp +++ b/src/widgets/kernel/qapplication.cpp @@ -1181,7 +1181,7 @@ void QApplicationPrivate::handlePaletteChanged(const char *className) } #if QT_CONFIG(graphicsview) - for (auto scene : qAsConst(scene_list)) + for (auto scene : std::as_const(scene_list)) QCoreApplication::sendEvent(scene, &event); #endif @@ -1631,7 +1631,8 @@ void QApplication::aboutQt() bool QApplication::event(QEvent *e) { Q_D(QApplication); - if (e->type() == QEvent::Quit) { + switch (e->type()) { + case QEvent::Quit: // FIXME: This logic first tries to close all windows, and then // checks whether it was successful, but the conditions used in // closeAllWindows() differ from the verification logic below. @@ -1651,7 +1652,7 @@ bool QApplication::event(QEvent *e) // closeAllWindows(). FIXME: Unify all this close magic through closeAllWindows. return QCoreApplication::event(e); #ifndef Q_OS_WIN - } else if (e->type() == QEvent::LocaleChange) { + case QEvent::LocaleChange: { // on Windows the event propagation is taken care by the // WM_SETTINGCHANGE event handler. const QWidgetList list = topLevelWidgets(); @@ -1661,8 +1662,10 @@ bool QApplication::event(QEvent *e) w->d_func()->setLocale_helper(QLocale(), true); } } + break; + } #endif - } else if (e->type() == QEvent::Timer) { + case QEvent::Timer: { QTimerEvent *te = static_cast<QTimerEvent*>(e); Q_ASSERT(te != nullptr); if (te->timerId() == d->toolTipWakeUp.timerId()) { @@ -1691,15 +1694,16 @@ bool QApplication::event(QEvent *e) } else if (te->timerId() == d->toolTipFallAsleep.timerId()) { d->toolTipFallAsleep.stop(); } + break; + } #if QT_CONFIG(whatsthis) - } else if (e->type() == QEvent::EnterWhatsThisMode) { + case QEvent::EnterWhatsThisMode: QWhatsThis::enterWhatsThisMode(); return true; #endif - } - - if (e->type() == QEvent::LanguageChange || e->type() == QEvent::ApplicationFontChange || - e->type() == QEvent::ApplicationPaletteChange) { + case QEvent::LanguageChange: + case QEvent::ApplicationFontChange: + case QEvent::ApplicationPaletteChange: { // QGuiApplication::event does not account for the cases where // there is a top level widget without a window handle. So they // need to have the event posted here @@ -1708,6 +1712,10 @@ bool QApplication::event(QEvent *e) if (!w->windowHandle() && (w->windowType() != Qt::Desktop)) postEvent(w, new QEvent(e->type())); } + break; + } + default: + break; } return QGuiApplication::event(e); @@ -2062,7 +2070,7 @@ void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave, con const QPointF globalPos = qIsInf(globalPosF.x()) ? QPointF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX) : globalPosF; - const QPointF windowPos = qAsConst(enterList).back()->window()->mapFromGlobal(globalPos); + const QPointF windowPos = std::as_const(enterList).back()->window()->mapFromGlobal(globalPos); for (auto it = enterList.crbegin(), end = enterList.crend(); it != end; ++it) { auto *w = *it; if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, nullptr)) { @@ -2071,8 +2079,9 @@ void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave, con QCoreApplication::sendEvent(w, &enterEvent); if (w->testAttribute(Qt::WA_Hover) && (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) { - QHoverEvent he(QEvent::HoverEnter, localPos, QPointF(-1, -1), globalPos, + QHoverEvent he(QEvent::HoverEnter, windowPos, QPointF(-1, -1), globalPos, QGuiApplication::keyboardModifiers()); + QMutableEventPoint::setPosition(he.point(0), localPos); qApp->d_func()->notify_helper(w, &he); } } @@ -2170,7 +2179,7 @@ bool QApplicationPrivate::isWindowBlocked(QWindow *window, QWindow **blockingWin return false; } - for (int i = 0; i < modalWindowList.count(); ++i) { + for (int i = 0; i < modalWindowList.size(); ++i) { QWindow *modalWindow = modalWindowList.at(i); // A window is not blocked by another modal window if the two are @@ -2505,7 +2514,7 @@ void QApplication::setStartDragTime(int ms) The default value is 500 ms. - \sa startDragDistance(), {Drag and Drop} + \sa startDragDistance(), {Drag and Drop in Qt}{Drag and Drop} */ int QApplication::startDragTime() @@ -2544,7 +2553,7 @@ void QApplication::setStartDragDistance(int l) The default value (if the platform doesn't provide a different default) is 10 pixels. - \sa startDragTime(), QPoint::manhattanLength(), {Drag and Drop} + \sa startDragTime(), QPoint::manhattanLength(), {Drag and Drop in Qt}{Drag and Drop} */ int QApplication::startDragDistance() @@ -2815,7 +2824,8 @@ bool QApplication::notify(QObject *receiver, QEvent *e) while (w) { if (w->testAttribute(Qt::WA_Hover) && (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) { - QHoverEvent he(QEvent::HoverMove, relpos, mouse->globalPosition(), relpos - diff, mouse->modifiers()); + QHoverEvent he(QEvent::HoverMove, mouse->scenePosition(), mouse->globalPosition(), relpos - diff, mouse->modifiers()); + QMutableEventPoint::setPosition(he.point(0), relpos); d->notify_helper(w, &he); } if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation)) @@ -3220,7 +3230,7 @@ bool QApplication::notify(QObject *receiver, QEvent *e) break; w = w->parentWidget(); } - for (QGesture *g : qAsConst(allGestures)) + for (QGesture *g : std::as_const(allGestures)) gestureEvent->setAccepted(g, false); gestureEvent->m_accept = false; // to make sure we check individual gestures break; @@ -3371,7 +3381,7 @@ void QApplicationPrivate::closePopup(QWidget *popup) qt_popup_down = nullptr; } - if (QApplicationPrivate::popupWidgets->count() == 0) { // this was the last popup + if (QApplicationPrivate::popupWidgets->size() == 0) { // this was the last popup delete QApplicationPrivate::popupWidgets; QApplicationPrivate::popupWidgets = nullptr; qt_popup_down_closed = false; @@ -3416,7 +3426,7 @@ void QApplicationPrivate::closePopup(QWidget *popup) // can become nullptr due to setFocus() above if (QApplicationPrivate::popupWidgets && - QApplicationPrivate::popupWidgets->count() == 1) // grab mouse/keyboard + QApplicationPrivate::popupWidgets->size() == 1) // grab mouse/keyboard grabForPopup(aw); } @@ -3431,7 +3441,7 @@ void QApplicationPrivate::openPopup(QWidget *popup) popupWidgets = new QWidgetList; popupWidgets->append(popup); // add to end of list - if (QApplicationPrivate::popupWidgets->count() == 1) // grab mouse/keyboard + if (QApplicationPrivate::popupWidgets->size() == 1) // grab mouse/keyboard grabForPopup(popup); // popups are not focus-handled by the window system (the first @@ -3439,7 +3449,7 @@ void QApplicationPrivate::openPopup(QWidget *popup) // new popup gets the focus if (popup->focusWidget()) { popup->focusWidget()->setFocus(Qt::PopupFocusReason); - } else if (popupWidgets->count() == 1) { // this was the first popup + } else if (popupWidgets->size() == 1) { // this was the first popup if (QWidget *fw = QApplication::focusWidget()) { QFocusEvent e(QEvent::FocusOut, Qt::PopupFocusReason); QCoreApplication::sendEvent(fw, &e); diff --git a/src/widgets/kernel/qboxlayout.cpp b/src/widgets/kernel/qboxlayout.cpp index d16d903f53..501883e85a 100644 --- a/src/widgets/kernel/qboxlayout.cpp +++ b/src/widgets/kernel/qboxlayout.cpp @@ -233,7 +233,7 @@ void QBoxLayoutPrivate::setupGeom() hasHfw = false; - int n = list.count(); + int n = list.size(); geomArray.clear(); QList<QLayoutStruct> a(n); @@ -365,7 +365,7 @@ void QBoxLayoutPrivate::setupGeom() void QBoxLayoutPrivate::calcHfw(int w) { QList<QLayoutStruct> &a = geomArray; - int n = a.count(); + int n = a.size(); int h = 0; int mh = 0; @@ -411,9 +411,9 @@ QLayoutItem* QBoxLayoutPrivate::replaceAt(int index, QLayoutItem *item) int QBoxLayoutPrivate::validateIndex(int index) const { if (index < 0) - return list.count(); // append + return list.size(); // append - Q_ASSERT_X(index >= 0 && index <= list.count(), "QBoxLayout::insert", "index out of range"); + Q_ASSERT_X(index >= 0 && index <= list.size(), "QBoxLayout::insert", "index out of range"); return index; } @@ -680,7 +680,7 @@ void QBoxLayout::invalidate() int QBoxLayout::count() const { Q_D(const QBoxLayout); - return d->list.count(); + return d->list.size(); } /*! @@ -689,7 +689,7 @@ int QBoxLayout::count() const QLayoutItem *QBoxLayout::itemAt(int index) const { Q_D(const QBoxLayout); - return index >= 0 && index < d->list.count() ? d->list.at(index)->item : nullptr; + return index >= 0 && index < d->list.size() ? d->list.at(index)->item : nullptr; } /*! @@ -698,7 +698,7 @@ QLayoutItem *QBoxLayout::itemAt(int index) const QLayoutItem *QBoxLayout::takeAt(int index) { Q_D(QBoxLayout); - if (index < 0 || index >= d->list.count()) + if (index < 0 || index >= d->list.size()) return nullptr; QBoxLayoutItem *b = d->list.takeAt(index); QLayoutItem *item = b->item; @@ -749,7 +749,7 @@ void QBoxLayout::setGeometry(const QRect &r) QList<QLayoutStruct> a = d->geomArray; int pos = horz(d->dir) ? s.x() : s.y(); int space = horz(d->dir) ? s.width() : s.height(); - int n = a.count(); + int n = a.size(); if (d->hasHfw && !horz(d->dir)) { for (int i = 0; i < n; i++) { QBoxLayoutItem *box = d->list.at(i); diff --git a/src/widgets/kernel/qformlayout.cpp b/src/widgets/kernel/qformlayout.cpp index fdce766c93..991b1429d7 100644 --- a/src/widgets/kernel/qformlayout.cpp +++ b/src/widgets/kernel/qformlayout.cpp @@ -480,6 +480,7 @@ void QFormLayoutPrivate::recalcHFW(int w) void QFormLayoutPrivate::setupHfwLayoutData() { + Q_Q(QFormLayout); // setupVerticalLayoutData must be called before this // setupHorizontalLayoutData must also be called before this // copies non hfw data into hfw @@ -504,6 +505,10 @@ void QFormLayoutPrivate::setupHfwLayoutData() QFormLayoutItem *label = m_matrix(i, 0); QFormLayoutItem *field = m_matrix(i, 1); + // ignore rows with only hidden items + if (!q->isRowVisible(i)) + continue; + if (label && label->vLayoutIndex > -1) { if (label->isHfw) { // We don't check sideBySide here, since a label is only @@ -681,9 +686,15 @@ void QFormLayoutPrivate::setupVerticalLayoutData(int width) QFormLayoutItem *label = m_matrix(i, 0); QFormLayoutItem *field = m_matrix(i, 1); - // Totally ignore empty rows or rows with only hidden items - if (!q->isRowVisible(i)) + // Ignore empty rows or rows with only hidden items, + // and invalidate their position in the layout. + if (!q->isRowVisible(i)) { + if (label) + label->vLayoutIndex = -1; + if (field) + field->vLayoutIndex = -1; continue; + } QSize min1; QSize min2; @@ -1643,7 +1654,7 @@ void QFormLayout::addItem(QLayoutItem *item) int QFormLayout::count() const { Q_D(const QFormLayout); - return d->m_things.count(); + return d->m_things.size(); } /*! @@ -2190,6 +2201,9 @@ void QFormLayoutPrivate::arrangeWidgets(const QList<QLayoutStruct> &layouts, QRe QFormLayoutItem *label = m_matrix(i, 0); QFormLayoutItem *field = m_matrix(i, 1); + if (!q->isRowVisible(i)) + continue; + if (label && label->vLayoutIndex > -1) { int height = layouts.at(label->vLayoutIndex).size; if ((label->expandingDirections() & Qt::Vertical) == 0) { diff --git a/src/widgets/kernel/qgridlayout.cpp b/src/widgets/kernel/qgridlayout.cpp index c3fb7d6993..7998567a21 100644 --- a/src/widgets/kernel/qgridlayout.cpp +++ b/src/widgets/kernel/qgridlayout.cpp @@ -109,18 +109,18 @@ public: int minimumHeightForWidth(int width, int hSpacing, int vSpacing); inline void getNextPos(int &row, int &col) { row = nextR; col = nextC; } - inline int count() const { return things.count(); } + inline int count() const { return things.size(); } QRect cellRect(int row, int col) const; inline QLayoutItem *itemAt(int index) const { - if (index >= 0 && index < things.count()) + if (index >= 0 && index < things.size()) return things.at(index)->item(); else return nullptr; } inline QLayoutItem *takeAt(int index) { Q_Q(QGridLayout); - if (index >= 0 && index < things.count()) { + if (index >= 0 && index < things.size()) { if (QGridBox *b = things.takeAt(index)) { QLayoutItem *item = b->takeItem(); if (QLayout *l = item->layout()) { @@ -148,7 +148,7 @@ public: } void getItemPosition(int index, int *row, int *column, int *rowSpan, int *columnSpan) const { - if (index >= 0 && index < things.count()) { + if (index >= 0 && index < things.size()) { const QGridBox *b = things.at(index); int toRow = b->toRow(rr); int toCol = b->toCol(cc); @@ -1294,7 +1294,7 @@ QLayoutItem *QGridLayout::itemAt(int index) const QLayoutItem *QGridLayout::itemAtPosition(int row, int column) const { Q_D(const QGridLayout); - int n = d->things.count(); + int n = d->things.size(); for (int i = 0; i < n; ++i) { QGridBox *box = d->things.at(i); if (row >= box->row && row <= box->toRow(d->rr) diff --git a/src/widgets/kernel/qstackedlayout.cpp b/src/widgets/kernel/qstackedlayout.cpp index 78177aa0cd..aca470fe1c 100644 --- a/src/widgets/kernel/qstackedlayout.cpp +++ b/src/widgets/kernel/qstackedlayout.cpp @@ -166,7 +166,7 @@ QStackedLayout::~QStackedLayout() int QStackedLayout::addWidget(QWidget *widget) { Q_D(QStackedLayout); - return insertWidget(d->list.count(), widget); + return insertWidget(d->list.size(), widget); } /*! @@ -187,9 +187,9 @@ int QStackedLayout::insertWidget(int index, QWidget *widget) { Q_D(QStackedLayout); addChildWidget(widget); - index = qMin(index, d->list.count()); + index = qMin(index, d->list.size()); if (index < 0) - index = d->list.count(); + index = d->list.size(); QWidgetItem *wi = QLayoutPrivate::createWidgetItem(this, widget); d->list.insert(index, wi); invalidate(); @@ -234,8 +234,8 @@ QLayoutItem *QStackedLayout::takeAt(int index) QLayoutItem *item = d->list.takeAt(index); if (index == d->index) { d->index = -1; - if ( d->list.count() > 0 ) { - int newIndex = (index == d->list.count()) ? index-1 : index; + if ( d->list.size() > 0 ) { + int newIndex = (index == d->list.size()) ? index-1 : index; setCurrentIndex(newIndex); } else { emit currentChanged(-1); @@ -403,7 +403,7 @@ QSize QStackedLayout::sizeHint() const { Q_D(const QStackedLayout); QSize s(0, 0); - int n = d->list.count(); + int n = d->list.size(); for (int i = 0; i < n; ++i) if (QWidget *widget = d->list.at(i)->widget()) { @@ -424,7 +424,7 @@ QSize QStackedLayout::minimumSize() const { Q_D(const QStackedLayout); QSize s(0, 0); - int n = d->list.count(); + int n = d->list.size(); for (int i = 0; i < n; ++i) if (QWidget *widget = d->list.at(i)->widget()) @@ -444,7 +444,7 @@ void QStackedLayout::setGeometry(const QRect &rect) widget->setGeometry(rect); break; case StackAll: - if (const int n = d->list.count()) + if (const int n = d->list.size()) for (int i = 0; i < n; ++i) if (QWidget *widget = d->list.at(i)->widget()) widget->setGeometry(rect); @@ -531,7 +531,7 @@ void QStackedLayout::setStackingMode(StackingMode stackingMode) return; d->stackingMode = stackingMode; - const int n = d->list.count(); + const int n = d->list.size(); if (n == 0) return; diff --git a/src/widgets/kernel/qtestsupport_widgets.cpp b/src/widgets/kernel/qtestsupport_widgets.cpp index ea8317db03..1141fcea0a 100644 --- a/src/widgets/kernel/qtestsupport_widgets.cpp +++ b/src/widgets/kernel/qtestsupport_widgets.cpp @@ -32,9 +32,16 @@ static bool qWaitForWidgetWindow(FunctorWindowGetter windowGetter, FunctorPredic /*! \since 5.0 - Waits for \a timeout milliseconds or until the \a widget's window is active. + Returns \c true if \a widget is active within \a timeout milliseconds. Otherwise returns \c false. - Returns \c true if \c widget's window is active within \a timeout milliseconds, otherwise returns \c false. + The method is useful in tests that call QWidget::show() and rely on the widget actually being + active (i.e. being visible and having focus) before proceeding. + + \note The method will time out and return \c false if another window prevents \a widget from + becoming active. + + \note Since focus is an exclusive property, \a widget may loose its focus to another window at + any time - even after the method has returned \c true. \sa qWaitForWindowExposed(), QWidget::isActiveWindow() */ @@ -56,20 +63,16 @@ Q_WIDGETS_EXPORT bool QTest::qWaitForWindowActive(QWidget *widget, int timeout) /*! \since 5.0 - Waits for \a timeout milliseconds or until the \a widget's window is exposed. - Returns \c true if \c widget's window is exposed within \a timeout milliseconds, otherwise returns \c false. - - This is mainly useful for asynchronous systems like X11, where a window will be mapped to screen some - time after being asked to show itself on the screen. + Returns \c true if \a widget is exposed within \a timeout milliseconds. Otherwise returns \c false. - Note that a window that is mapped to screen may still not be considered exposed if the window client - area is completely covered by other windows, or if the window is otherwise not visible. This function - will then time out when waiting for such a window. + The method is useful in tests that call QWidget::show() and rely on the widget actually being + being visible before proceeding. - A specific configuration where this happens is when using QGLWidget as a viewport widget on macOS: - The viewport widget gets the expose event, not the parent widget. + \note A window mapped to screen may still not be considered exposed, if the window client area is + not visible, e.g. because it is completely covered by other windows. + In such cases, the method will time out and return \c false. - \sa qWaitForWindowActive() + \sa qWaitForWindowActive(), QWidget::isVisible(), QWindow::isExposed() */ Q_WIDGETS_EXPORT bool QTest::qWaitForWindowExposed(QWidget *widget, int timeout) { @@ -83,7 +86,7 @@ namespace QTest { QTouchEventWidgetSequence::~QTouchEventWidgetSequence() { if (commitWhenDestroyed) - commit(); + QTouchEventWidgetSequence::commit(); } QTouchEventWidgetSequence& QTouchEventWidgetSequence::press(int touchId, const QPoint &pt, QWidget *widget) @@ -122,9 +125,9 @@ bool QTouchEventWidgetSequence::commit(bool processEvents) return ret; QThread::msleep(1); if (targetWindow) { - ret = qt_handleTouchEvent(targetWindow, device, points.values()); + ret = qt_handleTouchEventv2(targetWindow, device, points.values()); } else if (targetWidget) { - ret = qt_handleTouchEvent(targetWidget->windowHandle(), device, points.values()); + ret = qt_handleTouchEventv2(targetWidget->windowHandle(), device, points.values()); } if (processEvents) QCoreApplication::processEvents(); diff --git a/src/widgets/kernel/qtooltip.cpp b/src/widgets/kernel/qtooltip.cpp index b831c5265a..3166613199 100644 --- a/src/widgets/kernel/qtooltip.cpp +++ b/src/widgets/kernel/qtooltip.cpp @@ -157,7 +157,7 @@ QTipLabel::QTipLabel(const QString &text, const QPoint &pos, QWidget *w, int mse void QTipLabel::restartExpireTimer(int msecDisplayTime) { - int time = 10000 + 40 * qMax(0, text().length()-100); + int time = 10000 + 40 * qMax(0, text().size()-100); if (msecDisplayTime > 0) time = msecDisplayTime; expireTimer.start(time, this); diff --git a/src/widgets/kernel/qwidget.cpp b/src/widgets/kernel/qwidget.cpp index b28dcfc6f2..258e38d18c 100644 --- a/src/widgets/kernel/qwidget.cpp +++ b/src/widgets/kernel/qwidget.cpp @@ -515,7 +515,7 @@ void QWidget::setAutoFillBackground(bool enabled) button is held down. This can be useful during drag and drop operations. If you call \l{setMouseTracking()}{setMouseTracking}(true), you get mouse move events even when no buttons are held down. - (See also the \l{Drag and Drop} guide.) + (See also the \l{Drag and Drop in Qt}{Drag and Drop} guide.) \li keyReleaseEvent() is called whenever a key is released and while it is held down (if the key is auto-repeating). In that case, the widget will receive a pair of key release and key press event for @@ -1083,30 +1083,30 @@ static bool q_evaluateRhiConfigRecursive(const QWidget *w, QPlatformBackingStore *outType = QBackingStoreRhiSupport::surfaceTypeForConfig(config); return true; } - QObjectList children = w->children(); - for (int i = 0; i < children.size(); i++) { - if (children.at(i)->isWidgetType()) { - const QWidget *childWidget = qobject_cast<const QWidget *>(children.at(i)); - if (childWidget) { - if (q_evaluateRhiConfigRecursive(childWidget, outConfig, outType)) - return true; - } + for (const QObject *child : w->children()) { + if (const QWidget *childWidget = qobject_cast<const QWidget *>(child)) { + if (q_evaluateRhiConfigRecursive(childWidget, outConfig, outType)) + return true; } } return false; } -// First tries q_evaluateRhiConfigRecursive, then if that did not indicate that rhi is wanted, -// then checks env.vars or something else to see if we need to force using rhi-based composition. bool q_evaluateRhiConfig(const QWidget *w, QPlatformBackingStoreRhiConfig *outConfig, QSurface::SurfaceType *outType) { - if (q_evaluateRhiConfigRecursive(w, outConfig, outType)) { - qCDebug(lcWidgetPainting) << "Tree with root" << w << "evaluates to flushing with QRhi"; + // First, check env.vars. or other means that force the usage of rhi-based + // flushing with a specific graphics API. This takes precedence over what + // the widgets themselves declare. This is global, applying to all + // top-levels. + if (QBackingStoreRhiSupport::checkForceRhi(outConfig, outType)) { + qCDebug(lcWidgetPainting) << "Tree with root" << w << "evaluated to forced flushing with QRhi"; return true; } - if (QBackingStoreRhiSupport::checkForceRhi(outConfig, outType)) { - qCDebug(lcWidgetPainting) << "Tree with root" << w << "evaluated to forced flushing with QRhi"; + // Otherwise, check the widget hierarchy to see if there is a child (or + // ourselves) that declare the need for rhi-based composition. + if (q_evaluateRhiConfigRecursive(w, outConfig, outType)) { + qCDebug(lcWidgetPainting) << "Tree with root" << w << "evaluates to flushing with QRhi"; return true; } @@ -1432,7 +1432,7 @@ QWidget::~QWidget() #ifndef QT_NO_ACTION // remove all actions from this widget - for (auto action : qAsConst(d->actions)) { + for (auto action : std::as_const(d->actions)) { QActionPrivate *apriv = action->d_func(); apriv->associatedObjects.removeAll(this); } @@ -2201,7 +2201,7 @@ void QWidgetPrivate::updateIsTranslucent() if (QWindow *window = q->windowHandle()) { QSurfaceFormat format = window->format(); const int oldAlpha = format.alphaBufferSize(); - const int newAlpha = q->testAttribute(Qt::WA_TranslucentBackground)? 8 : 0; + const int newAlpha = q->testAttribute(Qt::WA_TranslucentBackground) ? 8 : -1; if (oldAlpha != newAlpha) { // QTBUG-85714: Do this only when the QWindow has not yet been create()'ed yet. // @@ -3133,7 +3133,7 @@ void QWidget::addAction(QAction *action) */ void QWidget::addActions(const QList<QAction *> &actions) { - for(int i = 0; i < actions.count(); i++) + for(int i = 0; i < actions.size(); i++) insertAction(nullptr, actions.at(i)); } @@ -3182,7 +3182,7 @@ void QWidget::insertAction(QAction *before, QAction *action) */ void QWidget::insertActions(QAction *before, const QList<QAction*> &actions) { - for(int i = 0; i < actions.count(); ++i) + for(int i = 0; i < actions.size(); ++i) insertAction(before, actions.at(i)); } @@ -3431,7 +3431,7 @@ void QWidgetPrivate::setEnabled_helper(bool enable) By default, this property is \c false. - \sa {Drag and Drop} + \sa {Drag and Drop in Qt}{Drag and Drop} */ bool QWidget::acceptDrops() const { @@ -6381,6 +6381,33 @@ void QWidget::setFocusProxy(QWidget * w) d->createExtra(); d->extra->focus_proxy = w; + if (w && isAncestorOf(w)) { + // If the focus proxy is a child of this (so this is a compound widget), then + // we need to make sure that this widget is immediately in front of its own children + // in the focus chain. Otherwise focusNextPrev_helper might jump over unrelated + // widgets that are positioned between this compound widget, and its proxy in + // the focus chain. + const QWidget *parentOfW = w->parentWidget(); + Q_ASSERT(parentOfW); // can't be nullptr since we are an ancestor of w + QWidget *firstChild = nullptr; + const auto childList = children(); + for (QObject *child : childList) { + if ((firstChild = qobject_cast<QWidget *>(child))) + break; + } + Q_ASSERT(firstChild); // can't be nullptr since w is a child + QWidget *oldNext = d->focus_next; + QWidget *oldPrev = d->focus_prev; + oldNext->d_func()->focus_prev = oldPrev; + oldPrev->d_func()->focus_next = oldNext; + + oldPrev = firstChild->d_func()->focus_prev; + d->focus_next = firstChild; + d->focus_prev = oldPrev; + oldPrev->d_func()->focus_next = this; + firstChild->d_func()->focus_prev = this; + } + if (moveFocusToProxy) setFocus(Qt::OtherFocusReason); } @@ -6516,15 +6543,11 @@ void QWidget::setFocus(Qt::FocusReason reason) QApplicationPrivate::setFocusWidget(f, reason); #if QT_CONFIG(accessibility) - // If the widget gets focus because its window becomes active, then the accessibility - // subsystem is already informed about the window opening, and also knows which child - // within the window has focus. Don't interrupt it by emitting another focus event. - if (reason != Qt::ActiveWindowFocusReason) { - // menus update the focus manually and this would create bogus events - if (!(f->inherits("QMenuBar") || f->inherits("QMenu") || f->inherits("QMenuItem"))) { - QAccessibleEvent event(f, QAccessible::Focus); - QAccessible::updateAccessibility(&event); - } + // menus update the focus manually and this would create bogus events + if (!(f->inherits("QMenuBar") || f->inherits("QMenu") || f->inherits("QMenuItem"))) + { + QAccessibleEvent event(f, QAccessible::Focus); + QAccessible::updateAccessibility(&event); } #endif #if QT_CONFIG(graphicsview) @@ -7076,8 +7099,8 @@ void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw) n->d_func()->focus_next = topLevel; } else { //repair the new list - n->d_func()->focus_next = q; - focus_prev = n; + n->d_func()->focus_next = q; + focus_prev = n; } } @@ -8339,6 +8362,7 @@ void QWidgetPrivate::showChildren(bool spontaneous) void QWidgetPrivate::hideChildren(bool spontaneous) { + Q_Q(QWidget); QList<QObject*> childList = children; for (int i = 0; i < childList.size(); ++i) { QWidget *widget = qobject_cast<QWidget*>(childList.at(i)); @@ -8370,6 +8394,14 @@ void QWidgetPrivate::hideChildren(bool spontaneous) } #endif } + + // If the window of this widget is not closed, then the leave event + // will eventually handle the widget under mouse use case. + // Otherwise, we need to explicitly handle it here. + if (QWidget* widgetWindow = q->window(); + widgetWindow && widgetWindow->data->is_closing) { + q->setAttribute(Qt::WA_UnderMouse, false); + } } /*! @@ -9004,7 +9036,7 @@ bool QWidget::event(QEvent *event) break; #if QT_CONFIG(menu) case Qt::ActionsContextMenu: - if (d->actions.count()) { + if (d->actions.size()) { QMenu::exec(d->actions, static_cast<QContextMenuEvent *>(event)->globalPos(), nullptr, this); break; @@ -9234,7 +9266,7 @@ bool QWidget::event(QEvent *event) break; case QEvent::DynamicPropertyChange: { const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName(); - if (propName.length() == 13 && !qstrncmp(propName, "_q_customDpi", 12)) { + if (propName.size() == 13 && !qstrncmp(propName, "_q_customDpi", 12)) { uint value = property(propName.constData()).toUInt(); if (!d->extra) d->createExtra(); @@ -10691,6 +10723,9 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f) QWidget *newtlw = window(); if (oldtlw != newtlw) { QSurface::SurfaceType surfaceType = QSurface::RasterSurface; + // Only evaluate the reparented subtree. While it might be tempting to + // do it on newtlw instead, the performance implications of that are + // problematic when it comes to large widget trees. if (q_evaluateRhiConfig(this, nullptr, &surfaceType)) { newtlw->d_func()->usesRhiFlush = true; if (QWindow *w = newtlw->windowHandle()) { diff --git a/src/widgets/kernel/qwidgetaction.cpp b/src/widgets/kernel/qwidgetaction.cpp index 1f2fa5dea3..4a3fb2be89 100644 --- a/src/widgets/kernel/qwidgetaction.cpp +++ b/src/widgets/kernel/qwidgetaction.cpp @@ -82,7 +82,7 @@ QWidgetAction::QWidgetAction(QObject *parent) QWidgetAction::~QWidgetAction() { Q_D(QWidgetAction); - for (int i = 0; i < d->createdWidgets.count(); ++i) + for (int i = 0; i < d->createdWidgets.size(); ++i) disconnect(d->createdWidgets.at(i), SIGNAL(destroyed(QObject*)), this, SLOT(_q_widgetDestroyed(QObject*))); QList<QWidget *> widgetsToDelete = d->createdWidgets; @@ -190,7 +190,7 @@ bool QWidgetAction::event(QEvent *event) if (event->type() == QEvent::ActionChanged) { if (d->defaultWidget) d->defaultWidget->setEnabled(isEnabled()); - for (int i = 0; i < d->createdWidgets.count(); ++i) + for (int i = 0; i < d->createdWidgets.size(); ++i) d->createdWidgets.at(i)->setEnabled(isEnabled()); } return QAction::event(event); diff --git a/src/widgets/kernel/qwidgetrepaintmanager.cpp b/src/widgets/kernel/qwidgetrepaintmanager.cpp index 69ab7de1af..7549c929a5 100644 --- a/src/widgets/kernel/qwidgetrepaintmanager.cpp +++ b/src/widgets/kernel/qwidgetrepaintmanager.cpp @@ -126,7 +126,7 @@ void QWidgetPrivate::invalidateBackingStore(const T &r) return; QTLWExtra *tlwExtra = q->window()->d_func()->maybeTopData(); - if (!tlwExtra || !tlwExtra->backingStore) + if (!tlwExtra || !tlwExtra->backingStore || !tlwExtra->repaintManager) return; T clipped(r); @@ -302,7 +302,7 @@ void QWidgetRepaintManager::removeDirtyWidget(QWidget *w) needsFlushWidgets.removeAll(w); QWidgetPrivate *wd = w->d_func(); - const int n = wd->children.count(); + const int n = wd->children.size(); for (int i = 0; i < n; ++i) { if (QWidget *child = qobject_cast<QWidget*>(wd->children.at(i))) removeDirtyWidget(child); @@ -565,7 +565,7 @@ static void findAllTextureWidgetsRecursively(QWidget *tlw, QWidget *widget) if (!tl->isEmpty()) QWidgetPrivate::get(tlw)->topData()->widgetTextures.push_back(std::move(tl)); // Native child widgets, if there was any, get their own separate QPlatformTextureList. - for (QWidget *ncw : qAsConst(nativeChildren)) { + for (QWidget *ncw : std::as_const(nativeChildren)) { if (QWidgetPrivate::get(ncw)->textureChildSeen) findAllTextureWidgetsRecursively(tlw, ncw); } @@ -808,7 +808,7 @@ void QWidgetRepaintManager::paintAndFlush() // texture content changes. Check if we have such widgets in the special // dirty list. QVarLengthArray<QWidget *, 16> paintPending; - const int numPaintPending = dirtyRenderToTextureWidgets.count(); + const int numPaintPending = dirtyRenderToTextureWidgets.size(); paintPending.reserve(numPaintPending); for (int i = 0; i < numPaintPending; ++i) { QWidget *w = dirtyRenderToTextureWidgets.at(i); @@ -850,7 +850,7 @@ void QWidgetRepaintManager::paintAndFlush() } } } - for (int i = 0; i < dirtyRenderToTextureWidgets.count(); ++i) + for (int i = 0; i < dirtyRenderToTextureWidgets.size(); ++i) resetWidget(dirtyRenderToTextureWidgets.at(i)); dirtyRenderToTextureWidgets.clear(); @@ -1032,7 +1032,7 @@ void QWidgetRepaintManager::flush(QWidget *widget, const QRegion ®ion, QPlatf if (widget != tlw) offset += widget->mapTo(tlw, QPoint()); - if (widget->d_func()->usesRhiFlush) { + if (tlw->d_func()->usesRhiFlush) { QRhi *rhi = store->handle()->rhi(); qCDebug(lcWidgetPainting) << "Flushing" << region << "of" << widget << "with QRhi" << rhi @@ -1133,7 +1133,7 @@ QRegion QWidgetRepaintManager::staticContents(QWidget *parent, const QRect &with return region; const bool clipToRect = !withinClipRect.isEmpty(); - const int count = staticWidgets.count(); + const int count = staticWidgets.size(); for (int i = 0; i < count; ++i) { QWidget *w = staticWidgets.at(i); QWidgetPrivate *wd = w->d_func(); diff --git a/src/widgets/kernel/qwidgetwindow.cpp b/src/widgets/kernel/qwidgetwindow.cpp index 61dfa5b2f1..626994fc2d 100644 --- a/src/widgets/kernel/qwidgetwindow.cpp +++ b/src/widgets/kernel/qwidgetwindow.cpp @@ -1051,11 +1051,10 @@ void QWidgetWindow::handleTabletEvent(QTabletEvent *event) if (!widget) { widget = m_widget->childAt(event->position().toPoint()); - if (event->type() == QEvent::TabletPress) { - if (!widget) - widget = m_widget; + if (!widget) + widget = m_widget; + if (event->type() == QEvent::TabletPress) qt_tablet_target = widget; - } } if (widget) { diff --git a/src/widgets/styles/qcommonstyle.cpp b/src/widgets/styles/qcommonstyle.cpp index bf6aca0380..7d3af8b372 100644 --- a/src/widgets/styles/qcommonstyle.cpp +++ b/src/widgets/styles/qcommonstyle.cpp @@ -653,7 +653,7 @@ void QCommonStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, Q if (cg == QPalette::Normal && !(vopt->state & QStyle::State_Active)) cg = QPalette::Inactive; - if ((vopt->state & QStyle::State_Selected) && proxy()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, opt, widget)) + if ((vopt->state & QStyle::State_Selected) && vopt->showDecorationSelected) p->fillRect(vopt->rect, vopt->palette.brush(cg, QPalette::Highlight)); else if (vopt->features & QStyleOptionViewItem::Alternate) p->fillRect(vopt->rect, vopt->palette.brush(cg, QPalette::AlternateBase)); @@ -1655,8 +1655,9 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt, alignment |= Qt::TextHideMnemonic; rect.translate(shiftX, shiftY); p->setFont(toolbutton->font); + const QString text = d->toolButtonElideText(toolbutton, rect, alignment); proxy()->drawItemText(p, rect, alignment, toolbutton->palette, - opt->state & State_Enabled, toolbutton->text, + opt->state & State_Enabled, text, QPalette::ButtonText); } else { QPixmap pm; @@ -6350,7 +6351,7 @@ QIcon QCommonStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption QIcon::Normal, QIcon::On); icon.addFile(iconResourcePrefix() + u"standardbutton-closetab-hover-16.png", QSize(16, 16), QIcon::Active, QIcon::Off); - icon.addFile(iconResourcePrefix() + u"standardbutton-closetab-hover-16.png", QSize(32, 32), + icon.addFile(iconResourcePrefix() + u"standardbutton-closetab-hover-32.png", QSize(32, 32), QIcon::Active, QIcon::Off); break; default: diff --git a/src/widgets/styles/qproxystyle.cpp b/src/widgets/styles/qproxystyle.cpp index 6cca56f5b5..a85c40a329 100644 --- a/src/widgets/styles/qproxystyle.cpp +++ b/src/widgets/styles/qproxystyle.cpp @@ -348,7 +348,18 @@ void QProxyStyle::unpolish(QApplication *app) */ bool QProxyStyle::event(QEvent *e) { - // ### Qt 7: remove this override + Q_D (QProxyStyle); + + switch (e->type()) { + // The Mac style relies on these events in order to set the focus frame + case QEvent::FocusIn: + case QEvent::FocusOut: + d->ensureBaseStyle(); + return QApplication::sendEvent(d->baseStyle, e); + default: + break; + } + return QCommonStyle::event(e); } diff --git a/src/widgets/styles/qstylepainter.h b/src/widgets/styles/qstylepainter.h index 65664b776e..240ffbd137 100644 --- a/src/widgets/styles/qstylepainter.h +++ b/src/widgets/styles/qstylepainter.h @@ -26,7 +26,7 @@ public: const bool res = QPainter::begin(pd); setRenderHint(QPainter::SmoothPixmapTransform); return res; - }; + } inline void drawPrimitive(QStyle::PrimitiveElement pe, const QStyleOption &opt); inline void drawControl(QStyle::ControlElement ce, const QStyleOption &opt); inline void drawComplexControl(QStyle::ComplexControl cc, const QStyleOptionComplex &opt); diff --git a/src/widgets/styles/qstylesheetstyle.cpp b/src/widgets/styles/qstylesheetstyle.cpp index 6abef62835..51426f1609 100644 --- a/src/widgets/styles/qstylesheetstyle.cpp +++ b/src/widgets/styles/qstylesheetstyle.cpp @@ -714,7 +714,7 @@ static const int numKnownStyleHints = sizeof(knownStyleHints)/sizeof(knownStyleH static QList<QVariant> subControlLayout(const QString& layout) { QList<QVariant> buttons; - for (int i = 0; i < layout.length(); i++) { + for (int i = 0; i < layout.size(); i++) { int button = layout[i].toLatin1(); switch (button) { case 'm': @@ -980,7 +980,7 @@ QRenderRule::QRenderRule(const QList<Declaration> &declarations, const QObject * palette = QToolTip::palette(); #endif - for (int i = 0; i < declarations.count(); i++) { + for (int i = 0; i < declarations.size(); i++) { const Declaration& decl = declarations.at(i); if (decl.d->propertyId == BorderImage) { QString uri; @@ -1056,7 +1056,7 @@ QRenderRule::QRenderRule(const QList<Declaration> &declarations, const QObject * } else if (hintName.endsWith("icon"_L1)) { hintValue = decl.iconValue(); } else if (hintName == "button-layout"_L1 - && decl.d->values.count() != 0 && decl.d->values.at(0).type == Value::String) { + && decl.d->values.size() != 0 && decl.d->values.at(0).type == Value::String) { hintValue = subControlLayout(decl.d->values.at(0).variant.toString()); } else { int integer; @@ -1474,7 +1474,11 @@ void QRenderRule::configurePalette(QPalette *p, QPalette::ColorGroup cg, const Q p->setBrush(cg, w->foregroundRole(), pal->foreground); p->setBrush(cg, QPalette::WindowText, pal->foreground); p->setBrush(cg, QPalette::Text, pal->foreground); - p->setBrush(cg, QPalette::PlaceholderText, pal->foreground); + QColor phColor(pal->foreground.color()); + phColor.setAlpha((phColor.alpha() + 1) / 2); + QBrush placeholder = pal->foreground; + placeholder.setColor(phColor); + p->setBrush(cg, QPalette::PlaceholderText, placeholder); } if (pal->selectionBackground.style() != Qt::NoBrush) p->setBrush(cg, QPalette::Highlight, pal->selectionBackground); @@ -1597,7 +1601,7 @@ public: #endif do { const ushort *uc = (const ushort *)nodeName.constData(); - const ushort *e = uc + nodeName.length(); + const ushort *e = uc + nodeName.size(); const uchar *c = (const uchar *)metaObject->className(); while (*c && uc != e && (*uc == *c || (*c == ':' && *uc == '-'))) { ++uc; @@ -1694,8 +1698,8 @@ QList<QCss::StyleRule> QStyleSheetStyle::styleRules(const QObject *obj) const objectSs.append(ss); } - for (int i = 0; i < objectSs.count(); i++) - objectSs[i].depth = objectSs.count() - i + 2; + for (int i = 0; i < objectSs.size(); i++) + objectSs[i].depth = objectSs.size() - i + 2; styleSelector.styleSheets += objectSs; @@ -1712,7 +1716,7 @@ static QList<Declaration> declarations(const QList<StyleRule> &styleRules, const quint64 pseudoClass = PseudoClass_Unspecified) { QList<Declaration> decls; - for (int i = 0; i < styleRules.count(); i++) { + for (int i = 0; i < styleRules.size(); i++) { const Selector& selector = styleRules.at(i).selectors.at(0); // Rules with pseudo elements don't cascade. This is an intentional // diversion for CSS @@ -1842,7 +1846,7 @@ QRenderRule QStyleSheetStyle::renderRule(const QObject *obj, int element, quint6 quint64 stateMask = 0; const QList<StyleRule> rules = styleRules(obj); - for (int i = 0; i < rules.count(); i++) { + for (int i = 0; i < rules.size(); i++) { const Selector& selector = rules.at(i).selectors.at(0); quint64 negated = 0; stateMask |= selector.pseudoClass(&negated); @@ -2164,7 +2168,7 @@ bool QStyleSheetStyle::hasStyleRule(const QObject *obj, int part) const } QString pseudoElement = QLatin1StringView(knownPseudoElements[part].name); - for (int i = 0; i < rules.count(); i++) { + for (int i = 0; i < rules.size(); i++) { const Selector& selector = rules.at(i).selectors.at(0); if (pseudoElement.compare(selector.pseudoElement(), Qt::CaseInsensitive) == 0) { cache[part] = true; @@ -2635,7 +2639,7 @@ void QStyleSheetStyle::setProperties(QWidget *w) { // scan decls for final occurrence of each "qproperty" QDuplicateTracker<QString> propertySet(decls.size()); - for (int i = decls.count() - 1; i >= 0; --i) { + for (int i = decls.size() - 1; i >= 0; --i) { const QString property = decls.at(i).d->property; if (!property.startsWith("qproperty-"_L1, Qt::CaseInsensitive)) continue; @@ -2644,7 +2648,7 @@ void QStyleSheetStyle::setProperties(QWidget *w) } } - for (int i = finals.count() - 1; i >= 0; --i) { + for (int i = finals.size() - 1; i >= 0; --i) { const Declaration &decl = decls.at(finals[i]); QStringView property = decl.d->property; property = property.mid(10); // strip "qproperty-" @@ -2801,7 +2805,7 @@ static void updateObjects(const QList<const QObject *>& objects) QCoreApplication::sendEvent(widget, &event); QList<const QObject *> children; children.reserve(widget->children().size() + 1); - for (auto child: qAsConst(widget->children())) + for (auto child: std::as_const(widget->children())) children.append(child); updateObjects(children); } @@ -2896,7 +2900,7 @@ void QStyleSheetStyle::polish(QWidget *w) //set the WA_Hover attribute if one of the selector depends of the hover state QList<StyleRule> rules = styleRules(w); - for (int i = 0; i < rules.count(); i++) { + for (int i = 0; i < rules.size(); i++) { const Selector& selector = rules.at(i).selectors.at(0); quint64 negated = 0; quint64 cssClass = selector.pseudoClass(&negated); @@ -2986,7 +2990,7 @@ void QStyleSheetStyle::repolish(QWidget *w) { QList<const QObject *> children; children.reserve(w->children().size() + 1); - for (auto child: qAsConst(w->children())) + for (auto child: std::as_const(w->children())) children.append(child); children.append(w); styleSheetCaches->styleSheetCache.remove(w); @@ -3484,7 +3488,7 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC QStyleOptionComplex optCopy(*opt); optCopy.subControls = { }; - for (int i = 0; i < layout.count(); i++) { + for (int i = 0; i < layout.size(); i++) { int layoutButton = layout[i].toInt(); if (layoutButton < PseudoElement_MdiCloseButton || layoutButton > PseudoElement_MdiNormalButton) @@ -4730,10 +4734,7 @@ void QStyleSheetStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *op if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) { QRenderRule subRule = renderRule(w, opt, PseudoElement_TreeViewBranch); if (subRule.hasDrawable()) { - if ((vopt->state & QStyle::State_Selected) && vopt->showDecorationSelected) - p->fillRect(vopt->rect, vopt->palette.highlight()); - else if (vopt->features & QStyleOptionViewItem::Alternate) - p->fillRect(vopt->rect, vopt->palette.alternateBase()); + proxy()->drawPrimitive(PE_PanelItemViewRow, vopt, p, w); subRule.drawRule(p, opt->rect); } else { baseStyle()->drawPrimitive(pe, vopt, p, w); @@ -4801,6 +4802,17 @@ void QStyleSheetStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *op pseudoElement = PseudoElement_DockWidgetSeparator; break; + case PE_PanelItemViewRow: + // For compatibility reasons, QTreeView draws different parts of + // the background of an item row separately, before calling the + // delegate to draw the item. The row background of an item is + // however not separately styleable through a style sheet, but + // only indirectly through the background of the item. To get the + // same background for all parts drawn by QTreeView, we have to + // use the background rule for the item here. + if (renderRule(w, opt, PseudoElement_ViewItem).hasBackground()) + pseudoElement = PseudoElement_ViewItem; + break; case PE_PanelItemViewItem: pseudoElement = PseudoElement_ViewItem; break; @@ -5087,7 +5099,7 @@ int QStyleSheetStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const break; case PM_ScrollView_ScrollBarOverlap: - if (!rule.hasNativeBorder() || rule.hasBox()) + if (!proxy()->styleHint(SH_ScrollBar_Transient, opt, w)) return 0; break; #endif // QT_CONFIG(scrollbar) @@ -5457,7 +5469,7 @@ QSize QStyleSheetStyle::sizeFromContents(ContentsType ct, const QStyleOption *op layout = subControlLayout("mNX"_L1); int width = 0, height = 0; - for (int i = 0; i < layout.count(); i++) { + for (int i = 0; i < layout.size(); i++) { int layoutButton = layout[i].toInt(); if (layoutButton < PseudoElement_MdiCloseButton || layoutButton > PseudoElement_MdiNormalButton) @@ -5697,7 +5709,7 @@ int QStyleSheetStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWi case SH_TitleBar_ShowToolTipsOnButtons: s = "titlebar-show-tooltips-on-buttons"_L1; break; case SH_Widget_Animation_Duration: s = "widget-animation-duration"_L1; break; case SH_ScrollBar_Transient: - if (!rule.hasNativeBorder() || rule.hasBox()) + if (!rule.hasNativeBorder() || rule.hasBox() || rule.hasDrawable()) return 0; break; default: break; @@ -6024,7 +6036,7 @@ QRect QStyleSheetStyle::subControlRect(ComplexControl cc, const QStyleOptionComp int x = 0, width = 0; QRenderRule subRule; - for (int i = 0; i < layout.count(); i++) { + for (int i = 0; i < layout.size(); i++) { int layoutButton = layout[i].toInt(); if (layoutButton < PseudoElement_MdiCloseButton || layoutButton > PseudoElement_MdiNormalButton) diff --git a/src/widgets/util/qcompleter.cpp b/src/widgets/util/qcompleter.cpp index abf3566e1c..1b519bf4c5 100644 --- a/src/widgets/util/qcompleter.cpp +++ b/src/widgets/util/qcompleter.cpp @@ -326,7 +326,7 @@ int QCompletionModel::rowCount(const QModelIndex &parent) const if (showAll) { // Show all items below current parent, even if we have no valid matches - if (engine->curParts.count() != 1 && !engine->matchCount() + if (engine->curParts.size() != 1 && !engine->matchCount() && !engine->curParent.isValid()) return 0; return d->model->rowCount(engine->curParent); @@ -411,7 +411,7 @@ void QCompletionEngine::filter(const QStringList& parts) return; QModelIndex parent; - for (int i = 0; i < curParts.count() - 1; i++) { + for (int i = 0; i < curParts.size() - 1; i++) { QString part = curParts.at(i); int emi = filter(part, parent, -1).exactMatchIndex; if (emi == -1) @@ -432,7 +432,7 @@ void QCompletionEngine::filter(const QStringList& parts) QMatchData QCompletionEngine::filterHistory() { QAbstractItemModel *source = c->proxy->sourceModel(); - if (curParts.count() <= 1 || c->proxy->showAll || !source) + if (curParts.size() <= 1 || c->proxy->showAll || !source) return QMatchData(); #if QT_CONFIG(filesystemmodel) @@ -516,7 +516,7 @@ void QCompletionEngine::saveInCache(QString part, const QModelIndex& parent, con QMap<QModelIndex, CacheItem>::iterator it1 = cache.begin(); while (it1 != cache.end()) { CacheItem& ci = it1.value(); - int sz = ci.count()/2; + int sz = ci.size()/2; QMap<QString, QMatchData>::iterator it2 = ci.begin(); int i = 0; while (it2 != ci.end() && i < sz) { @@ -524,7 +524,7 @@ void QCompletionEngine::saveInCache(QString part, const QModelIndex& parent, con it2 = ci.erase(it2); i++; } - if (ci.count() == 0) { + if (ci.size() == 0) { it1 = cache.erase(it1); } else { ++it1; @@ -1811,7 +1811,7 @@ QString QCompleter::pathFromIndex(const QModelIndex& index) const } while (idx.isValid()); #if !defined(Q_OS_WIN) - if (list.count() == 1) // only the separator or some other text + if (list.size() == 1) // only the separator or some other text return list[0]; list[0].clear() ; // the join below will provide the separator #endif diff --git a/src/widgets/util/qcompleter_p.h b/src/widgets/util/qcompleter_p.h index 1cd001b4c1..b74de04031 100644 --- a/src/widgets/util/qcompleter_p.h +++ b/src/widgets/util/qcompleter_p.h @@ -78,7 +78,7 @@ public: QIndexMapper(int f, int t) : v(false), f(f), t(t) { } QIndexMapper(const QList<int> &vec) : v(true), vector(vec), f(-1), t(-1) { } - inline int count() const { return v ? vector.count() : t - f + 1; } + inline int count() const { return v ? vector.size() : t - f + 1; } inline int operator[] (int index) const { return v ? vector[index] : f + index; } inline int indexOf(int x) const { return v ? vector.indexOf(x) : ((t < f) ? -1 : x - f); } inline bool isValid() const { return !isEmpty(); } @@ -88,7 +88,7 @@ public: inline int last() const { return v ? vector.last() : t; } inline int from() const { Q_ASSERT(!v); return f; } inline int to() const { Q_ASSERT(!v); return t; } - inline int cost() const { return vector.count()+2; } + inline int cost() const { return vector.size()+2; } private: bool v; diff --git a/src/widgets/util/qflickgesture.cpp b/src/widgets/util/qflickgesture.cpp index 133878f691..128013d0e1 100644 --- a/src/widgets/util/qflickgesture.cpp +++ b/src/widgets/util/qflickgesture.cpp @@ -38,43 +38,19 @@ static QMouseEvent *copyMouseEvent(QEvent *e) case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseMove: { - QMouseEvent *me = static_cast<QMouseEvent *>(e); - QMouseEvent *cme = new QMouseEvent(me->type(), QPoint(0, 0), me->scenePosition(), me->globalPosition(), - me->button(), me->buttons(), me->modifiers(), me->source()); - return cme; + return static_cast<QMouseEvent *>(e->clone()); } #if QT_CONFIG(graphicsview) case QEvent::GraphicsSceneMousePress: case QEvent::GraphicsSceneMouseRelease: case QEvent::GraphicsSceneMouseMove: { QGraphicsSceneMouseEvent *me = static_cast<QGraphicsSceneMouseEvent *>(e); -#if 1 QEvent::Type met = me->type() == QEvent::GraphicsSceneMousePress ? QEvent::MouseButtonPress : (me->type() == QEvent::GraphicsSceneMouseRelease ? QEvent::MouseButtonRelease : QEvent::MouseMove); QMouseEvent *cme = new QMouseEvent(met, QPoint(0, 0), QPoint(0, 0), me->screenPos(), me->button(), me->buttons(), me->modifiers(), me->source()); + cme->setTimestamp(me->timestamp()); return cme; -#else - QGraphicsSceneMouseEvent *copy = new QGraphicsSceneMouseEvent(me->type()); - copy->setPos(me->pos()); - copy->setScenePos(me->scenePos()); - copy->setScreenPos(me->screenPos()); - for (int i = 0x1; i <= 0x10; i <<= 1) { - Qt::MouseButton button = Qt::MouseButton(i); - copy->setButtonDownPos(button, me->buttonDownPos(button)); - copy->setButtonDownScenePos(button, me->buttonDownScenePos(button)); - copy->setButtonDownScreenPos(button, me->buttonDownScreenPos(button)); - } - copy->setLastPos(me->lastPos()); - copy->setLastScenePos(me->lastScenePos()); - copy->setLastScreenPos(me->lastScreenPos()); - copy->setButtons(me->buttons()); - copy->setButton(me->button()); - copy->setModifiers(me->modifiers()); - copy->setSource(me->source()); - copy->setFlags(me->flags()); - return copy; -#endif } #endif // QT_CONFIG(graphicsview) default: @@ -190,22 +166,6 @@ public: mouseTarget = nullptr; } else if (mouseTarget) { // we did send a press, so we need to fake a release now - - // release all pressed mouse buttons - /* Qt::MouseButtons mouseButtons = QGuiApplication::mouseButtons(); - for (int i = 0; i < 32; ++i) { - if (mouseButtons & (1 << i)) { - Qt::MouseButton b = static_cast<Qt::MouseButton>(1 << i); - mouseButtons &= ~b; - QPoint farFarAway(-QWIDGETSIZE_MAX, -QWIDGETSIZE_MAX); - - qFGDebug() << "QFG: sending a fake mouse release at far-far-away to " << mouseTarget; - QMouseEvent re(QEvent::MouseButtonRelease, QPoint(), farFarAway, - b, mouseButtons, QGuiApplication::keyboardModifiers()); - sendMouseEvent(&re); - } - }*/ - QPoint farFarAway(-QWIDGETSIZE_MAX, -QWIDGETSIZE_MAX); qFGDebug() << "QFG: sending a fake mouse release at far-far-away to " << mouseTarget; @@ -265,6 +225,7 @@ protected: mouseTarget->topLevelWidget()->mapFromGlobal(me->globalPosition()), me->globalPosition(), me->button(), me->buttons(), me->modifiers(), me->source(), me->pointingDevice()); + copy.setTimestamp(me->timestamp()); qt_sendSpontaneousEvent(mouseTarget, ©); } @@ -520,14 +481,14 @@ QGestureRecognizer::Result QFlickGestureRecognizer::recognize(QGesture *state, inputType = QScroller::InputMove; if (te->pointingDevice()->type() == QInputDevice::DeviceType::TouchPad) { - if (te->points().count() != 2) // 2 fingers on pad + if (te->points().size() != 2) // 2 fingers on pad return Ignore; point = te->points().at(0).scenePressPosition() + ((te->points().at(0).scenePosition() - te->points().at(0).scenePressPosition()) + (te->points().at(1).scenePosition() - te->points().at(1).scenePressPosition())) / 2; } else { // TouchScreen - if (te->points().count() != 1) // 1 finger on screen + if (te->points().size() != 1) // 1 finger on screen return Ignore; point = te->points().at(0).scenePosition(); diff --git a/src/widgets/util/qscroller.cpp b/src/widgets/util/qscroller.cpp index e69b19feb1..385f3b3594 100644 --- a/src/widgets/util/qscroller.cpp +++ b/src/widgets/util/qscroller.cpp @@ -27,21 +27,16 @@ #include <qnumeric.h> #include <QtDebug> - +#include <QtCore/qloggingcategory.h> QT_BEGIN_NAMESPACE -bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event); - -//#define QSCROLLER_DEBUG +Q_LOGGING_CATEGORY(lcScroller, "qt.widgets.scroller") -#ifdef QSCROLLER_DEBUG -# define qScrollerDebug qDebug -#else -# define qScrollerDebug while (false) qDebug -#endif +bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event); +namespace { QDebug &operator<<(QDebug &dbg, const QScrollerPrivate::ScrollSegment &s) { dbg << "\n Time: start:" << s.startTime << " duration:" << s.deltaTime << " stop progress:" << s.stopProgress; @@ -49,7 +44,7 @@ QDebug &operator<<(QDebug &dbg, const QScrollerPrivate::ScrollSegment &s) dbg << "\n Curve: type:" << s.curve.type() << "\n"; return dbg; } - +} // anonymous namespace // a few helper operators to make the code below a lot more readable: // otherwise a lot of ifs would have to be multi-line to check both the x @@ -120,7 +115,8 @@ static qreal differentialForProgress(const QEasingCurve &curve, qreal pos) qreal right = (pos >= qreal(0.5)) ? pos : pos + qreal(dx); qreal d = (curve.valueForProgress(right) - curve.valueForProgress(left)) / qreal(dx); - //qScrollerDebug() << "differentialForProgress(type: " << curve.type() << ", pos: " << pos << ") = " << d; + qCDebug(lcScroller) << "differentialForProgress(type: " << curve.type() + << ", pos: " << pos << ") = " << d; return d; } @@ -132,7 +128,8 @@ static qreal progressForValue(const QEasingCurve &curve, qreal value) { if (Q_UNLIKELY(curve.type() >= QEasingCurve::InElastic && curve.type() < QEasingCurve::Custom)) { - qWarning("progressForValue(): QEasingCurves of type %d do not have an inverse, since they are not injective.", curve.type()); + qWarning("progressForValue(): QEasingCurves of type %d do not have an " + "inverse, since they are not injective.", curve.type()); return value; } if (value < qreal(0) || value > qreal(1)) @@ -574,14 +571,18 @@ QPointF QScroller::velocity() const if (!d->xSegments.isEmpty()) { const QScrollerPrivate::ScrollSegment &s = d->xSegments.head(); qreal progress = qreal(now - s.startTime) / qreal(s.deltaTime); - qreal v = qSign(s.deltaPos) * qreal(s.deltaTime) / qreal(1000) * sp->decelerationFactor * qreal(0.5) * differentialForProgress(s.curve, progress); + qreal v = qSign(s.deltaPos) * qreal(s.deltaTime) / qreal(1000) + * sp->decelerationFactor * qreal(0.5) + * differentialForProgress(s.curve, progress); vel.setX(v); } if (!d->ySegments.isEmpty()) { const QScrollerPrivate::ScrollSegment &s = d->ySegments.head(); qreal progress = qreal(now - s.startTime) / qreal(s.deltaTime); - qreal v = qSign(s.deltaPos) * qreal(s.deltaTime) / qreal(1000) * sp->decelerationFactor * qreal(0.5) * differentialForProgress(s.curve, progress); + qreal v = qSign(s.deltaPos) * qreal(s.deltaTime) / qreal(1000) + * sp->decelerationFactor * qreal(0.5) + * differentialForProgress(s.curve, progress); vel.setY(v); } return vel; @@ -650,7 +651,8 @@ void QScroller::scrollTo(const QPointF &pos, int scrollTime) if (!qIsNaN(snapY)) newpos.setY(snapY); - qScrollerDebug() << "QScroller::scrollTo(req:" << pos << " [pix] / snap:" << newpos << ", " << scrollTime << " [ms])"; + qCDebug(lcScroller) << "QScroller::scrollTo(req:" << pos << " [pix] / snap:" + << newpos << ", " << scrollTime << " [ms])"; if (newpos == d->contentPosition + d->overshootPosition) return; @@ -714,8 +716,9 @@ void QScroller::ensureVisible(const QRectF &rect, qreal xmargin, qreal ymargin, QSizeF visible = d->viewportSize; QRectF visibleRect(startPos, visible); - qScrollerDebug() << "QScroller::ensureVisible(" << rect << " [pix], " << xmargin << " [pix], " << ymargin << " [pix], " << scrollTime << "[ms])"; - qScrollerDebug() << " --> content position:" << d->contentPosition; + qCDebug(lcScroller) << "QScroller::ensureVisible(" << rect << " [pix], " << xmargin + << " [pix], " << ymargin << " [pix], " << scrollTime << "[ms])"; + qCDebug(lcScroller) << " --> content position:" << d->contentPosition; if (visibleRect.contains(marginRect)) return; @@ -943,7 +946,8 @@ bool QScroller::handleInput(Input input, const QPointF &position, qint64 timesta { Q_D(QScroller); - qScrollerDebug() << "QScroller::handleInput(" << input << ", " << d->stateName(d->state) << ", " << position << ", " << timestamp << ')'; + qCDebug(lcScroller) << "QScroller::handleInput(" << input << ", " << d->stateName(d->state) + << ", " << position << ", " << timestamp << ')'; struct statechange { State state; Input input; @@ -1012,7 +1016,8 @@ void QScrollerPrivate::updateVelocity(const QPointF &deltaPixelRaw, qint64 delta const QScrollerPropertiesPrivate *sp = properties.d.data(); QPointF deltaPixel = deltaPixelRaw; - qScrollerDebug() << "QScroller::updateVelocity(" << deltaPixelRaw << " [delta pix], " << deltaTime << " [delta ms])"; + qCDebug(lcScroller) << "QScroller::updateVelocity(" << deltaPixelRaw + << " [delta pix], " << deltaTime << " [delta ms])"; // faster than 2.5mm/ms seems bogus (that would be a screen height in ~20 ms) if (((deltaPixelRaw / qreal(deltaTime)).manhattanLength() / ((ppm.x() + ppm.y()) / 2) * 1000) > qreal(2.5)) @@ -1027,7 +1032,8 @@ void QScrollerPrivate::updateVelocity(const QPointF &deltaPixelRaw, qint64 delta // only smooth if we already have a release velocity and only if the // user hasn't stopped to move his finger for more than 100ms if ((releaseVelocity != QPointF(0, 0)) && (deltaTime < 100)) { - qScrollerDebug() << "SMOOTHED from " << newv << " to " << newv * smoothing + releaseVelocity * (qreal(1) - smoothing); + qCDebug(lcScroller) << "SMOOTHED from " << newv << " to " + << newv * smoothing + releaseVelocity * (qreal(1) - smoothing); // smooth x or y only if the new velocity is either 0 or at least in // the same direction of the release velocity if (!newv.x() || (qSign(releaseVelocity.x()) == qSign(newv.x()))) @@ -1035,15 +1041,17 @@ void QScrollerPrivate::updateVelocity(const QPointF &deltaPixelRaw, qint64 delta if (!newv.y() || (qSign(releaseVelocity.y()) == qSign(newv.y()))) newv.setY(newv.y() * smoothing + releaseVelocity.y() * (qreal(1) - smoothing)); } else - qScrollerDebug() << "NO SMOOTHING to " << newv; + qCDebug(lcScroller) << "NO SMOOTHING to " << newv; releaseVelocity.setX(qBound(-sp->maximumVelocity, newv.x(), sp->maximumVelocity)); releaseVelocity.setY(qBound(-sp->maximumVelocity, newv.y(), sp->maximumVelocity)); - qScrollerDebug() << " --> new velocity:" << releaseVelocity; + qCDebug(lcScroller) << " --> new velocity:" << releaseVelocity; } -void QScrollerPrivate::pushSegment(ScrollType type, qreal deltaTime, qreal stopProgress, qreal startPos, qreal deltaPos, qreal stopPos, QEasingCurve::Type curve, Qt::Orientation orientation) +void QScrollerPrivate::pushSegment(ScrollType type, qreal deltaTime, qreal stopProgress, + qreal startPos, qreal deltaPos, qreal stopPos, + QEasingCurve::Type curve, Qt::Orientation orientation) { if (startPos == stopPos || deltaPos == 0) return; @@ -1072,7 +1080,7 @@ void QScrollerPrivate::pushSegment(ScrollType type, qreal deltaTime, qreal stopP else ySegments.enqueue(s); - qScrollerDebug() << "+++ Added a new ScrollSegment: " << s; + qCDebug(lcScroller) << "+++ Added a new ScrollSegment: " << s; } @@ -1158,7 +1166,8 @@ bool QScrollerPrivate::scrollingSegmentsValid(Qt::Orientation orientation) const /*! \internal Creates the sections needed to scroll to the specific \a endPos to the segments queue. */ -void QScrollerPrivate::createScrollToSegments(qreal v, qreal deltaTime, qreal endPos, Qt::Orientation orientation, ScrollType type) +void QScrollerPrivate::createScrollToSegments(qreal v, qreal deltaTime, qreal endPos, + Qt::Orientation orientation, ScrollType type) { Q_UNUSED(v); @@ -1167,7 +1176,8 @@ void QScrollerPrivate::createScrollToSegments(qreal v, qreal deltaTime, qreal en else ySegments.clear(); - qScrollerDebug() << "+++ createScrollToSegments: t:" << deltaTime << "ep:" << endPos << "o:" << int(orientation); + qCDebug(lcScroller) << "+++ createScrollToSegments: t:" << deltaTime << "ep:" + << endPos << "o:" << int(orientation); const QScrollerPropertiesPrivate *sp = properties.d.data(); @@ -1175,8 +1185,10 @@ void QScrollerPrivate::createScrollToSegments(qreal v, qreal deltaTime, qreal en : contentPosition.y() + overshootPosition.y(); qreal deltaPos = (endPos - startPos) / 2; - pushSegment(type, deltaTime * qreal(0.3), qreal(1.0), startPos, deltaPos, startPos + deltaPos, QEasingCurve::InQuad, orientation); - pushSegment(type, deltaTime * qreal(0.7), qreal(1.0), startPos + deltaPos, deltaPos, endPos, sp->scrollingCurve.type(), orientation); + pushSegment(type, deltaTime * qreal(0.3), qreal(1.0), startPos, deltaPos, startPos + deltaPos, + QEasingCurve::InQuad, orientation); + pushSegment(type, deltaTime * qreal(0.7), qreal(1.0), startPos + deltaPos, deltaPos, endPos, + sp->scrollingCurve.type(), orientation); } /*! \internal @@ -1210,13 +1222,15 @@ void QScrollerPrivate::createScrollingSegments(qreal v, qreal startPos, bool noOvershoot = (policy == QScrollerProperties::OvershootAlwaysOff) || !sp->overshootScrollDistanceFactor; bool canOvershoot = !noOvershoot && (alwaysOvershoot || maxPos); - qScrollerDebug() << "+++ createScrollingSegments: s:" << startPos << "maxPos:" << maxPos << "o:" << int(orientation); + qCDebug(lcScroller) << "+++ createScrollingSegments: s:" << startPos << "maxPos:" << maxPos + << "o:" << int(orientation); - qScrollerDebug() << "v = " << v << ", decelerationFactor = " << sp->decelerationFactor << ", curveType = " << sp->scrollingCurve.type(); + qCDebug(lcScroller) << "v = " << v << ", decelerationFactor = " << sp->decelerationFactor + << ", curveType = " << sp->scrollingCurve.type(); qreal endPos = startPos + deltaPos; - qScrollerDebug() << " Real Delta:" << deltaPos; + qCDebug(lcScroller) << " Real Delta:" << deltaPos; // -- check if are in overshoot and end in overshoot if ((startPos < minPos && endPos < minPos) || @@ -1224,7 +1238,8 @@ void QScrollerPrivate::createScrollingSegments(qreal v, qreal startPos, qreal stopPos = endPos < minPos ? minPos : maxPos; qreal oDeltaTime = sp->overshootScrollTime; - pushSegment(ScrollTypeOvershoot, oDeltaTime * qreal(0.7), qreal(1.0), startPos, stopPos - startPos, stopPos, sp->scrollingCurve.type(), orientation); + pushSegment(ScrollTypeOvershoot, oDeltaTime * qreal(0.7), qreal(1.0), startPos, + stopPos - startPos, stopPos, sp->scrollingCurve.type(), orientation); return; } @@ -1233,7 +1248,7 @@ void QScrollerPrivate::createScrollingSegments(qreal v, qreal startPos, qreal lowerSnapPos = nextSnapPos(startPos, -1, orientation); qreal higherSnapPos = nextSnapPos(startPos, 1, orientation); - qScrollerDebug() << " Real Delta:" << lowerSnapPos << '-' << nextSnap << '-' <<higherSnapPos; + qCDebug(lcScroller) << " Real Delta:" << lowerSnapPos << '-' << nextSnap << '-' <<higherSnapPos; // - check if we can reach another snap point if (nextSnap > higherSnapPos || qIsNaN(higherSnapPos)) @@ -1243,7 +1258,7 @@ void QScrollerPrivate::createScrollingSegments(qreal v, qreal startPos, if (qAbs(v) < sp->minimumVelocity) { - qScrollerDebug() << "### below minimum Vel" << orientation; + qCDebug(lcScroller) << "### below minimum Vel" << orientation; // - no snap points or already at one if (qIsNaN(nextSnap) || nextSnap == startPos) @@ -1267,8 +1282,10 @@ void QScrollerPrivate::createScrollingSegments(qreal v, qreal startPos, deltaPos = endPos - startPos; qreal midPos = startPos + deltaPos * qreal(0.3); - pushSegment(ScrollTypeFlick, sp->snapTime * qreal(0.3), qreal(1.0), startPos, midPos - startPos, midPos, QEasingCurve::InQuad, orientation); - pushSegment(ScrollTypeFlick, sp->snapTime * qreal(0.7), qreal(1.0), midPos, endPos - midPos, endPos, sp->scrollingCurve.type(), orientation); + pushSegment(ScrollTypeFlick, sp->snapTime * qreal(0.3), qreal(1.0), startPos, + midPos - startPos, midPos, QEasingCurve::InQuad, orientation); + pushSegment(ScrollTypeFlick, sp->snapTime * qreal(0.7), qreal(1.0), midPos, + endPos - midPos, endPos, sp->scrollingCurve.type(), orientation); return; } @@ -1293,35 +1310,43 @@ void QScrollerPrivate::createScrollingSegments(qreal v, qreal startPos, } else if (endPos < minPos || endPos > maxPos) { qreal stopPos = endPos < minPos ? minPos : maxPos; - qScrollerDebug() << "Overshoot: delta:" << (stopPos - startPos); + qCDebug(lcScroller) << "Overshoot: delta:" << (stopPos - startPos); qreal stopProgress = progressForValue(sp->scrollingCurve, qAbs((stopPos - startPos) / deltaPos)); if (!canOvershoot) { - qScrollerDebug() << "Overshoot stopp:" << stopProgress; + qCDebug(lcScroller) << "Overshoot stopp:" << stopProgress; - pushSegment(ScrollTypeFlick, deltaTime, stopProgress, startPos, endPos, stopPos, sp->scrollingCurve.type(), orientation); + pushSegment(ScrollTypeFlick, deltaTime, stopProgress, startPos, endPos, stopPos, + sp->scrollingCurve.type(), orientation); } else { qreal oDeltaTime = sp->overshootScrollTime; qreal oStopProgress = qMin(stopProgress + oDeltaTime * qreal(0.3) / deltaTime, qreal(1)); qreal oDistance = startPos + deltaPos * sp->scrollingCurve.valueForProgress(oStopProgress) - stopPos; qreal oMaxDistance = qSign(oDistance) * (viewSize * sp->overshootScrollDistanceFactor); - qScrollerDebug() << "1 oDistance:" << oDistance << "Max:" << oMaxDistance << "stopP/oStopP" << stopProgress << oStopProgress; + qCDebug(lcScroller) << "1 oDistance:" << oDistance << "Max:" << oMaxDistance + << "stopP/oStopP" << stopProgress << oStopProgress; if (qAbs(oDistance) > qAbs(oMaxDistance)) { - oStopProgress = progressForValue(sp->scrollingCurve, qAbs((stopPos + oMaxDistance - startPos) / deltaPos)); + oStopProgress = progressForValue(sp->scrollingCurve, + qAbs((stopPos + oMaxDistance - startPos) / deltaPos)); oDistance = oMaxDistance; - qScrollerDebug() << "2 oDistance:" << oDistance << "Max:" << oMaxDistance << "stopP/oStopP" << stopProgress << oStopProgress; + qCDebug(lcScroller) << "2 oDistance:" << oDistance << "Max:" << oMaxDistance + << "stopP/oStopP" << stopProgress << oStopProgress; } - pushSegment(ScrollTypeFlick, deltaTime, oStopProgress, startPos, deltaPos, stopPos + oDistance, sp->scrollingCurve.type(), orientation); - pushSegment(ScrollTypeOvershoot, oDeltaTime * qreal(0.7), qreal(1.0), stopPos + oDistance, -oDistance, stopPos, sp->scrollingCurve.type(), orientation); + pushSegment(ScrollTypeFlick, deltaTime, oStopProgress, startPos, deltaPos, + stopPos + oDistance, sp->scrollingCurve.type(), orientation); + pushSegment(ScrollTypeOvershoot, oDeltaTime * qreal(0.7), qreal(1.0), + stopPos + oDistance, -oDistance, stopPos, sp->scrollingCurve.type(), + orientation); } return; } - pushSegment(ScrollTypeFlick, deltaTime, qreal(1.0), startPos, deltaPos, endPos, sp->scrollingCurve.type(), orientation); + pushSegment(ScrollTypeFlick, deltaTime, qreal(1.0), startPos, deltaPos, endPos, + sp->scrollingCurve.type(), orientation); } @@ -1346,8 +1371,10 @@ void QScrollerPrivate::createScrollingSegments(const QPointF &v, // deltaPos = pos(deltaTime) QVector2D vel(v); - qreal deltaTime = (qreal(2) * vel.length()) / (sp->decelerationFactor * differentialForProgress(sp->scrollingCurve, 0)); - QPointF deltaPos = (vel.normalized() * QVector2D(ppm)).toPointF() * deltaTime * deltaTime * qreal(0.5) * sp->decelerationFactor; + qreal deltaTime = (qreal(2) * vel.length()) + / (sp->decelerationFactor * differentialForProgress(sp->scrollingCurve, 0)); + QPointF deltaPos = (vel.normalized() * QVector2D(ppm)).toPointF() + * deltaTime * deltaTime * qreal(0.5) * sp->decelerationFactor; createScrollingSegments(v.x(), startPos.x(), deltaTime, deltaPos.x(), Qt::Horizontal); @@ -1365,7 +1392,8 @@ bool QScrollerPrivate::prepareScrolling(const QPointF &position) spe.ignore(); sendEvent(target, &spe); - qScrollerDebug() << "QScrollPrepareEvent returned from" << target << "with" << spe.isAccepted() << "mcp:" << spe.contentPosRange() << "cp:" << spe.contentPos(); + qCDebug(lcScroller) << "QScrollPrepareEvent returned from" << target << "with" << spe.isAccepted() + << "mcp:" << spe.contentPosRange() << "cp:" << spe.contentPos(); if (spe.isAccepted()) { QPointF oldContentPos = contentPosition + overshootPosition; QPointF contentDelta = spe.contentPos() - oldContentPos; @@ -1382,10 +1410,10 @@ bool QScrollerPrivate::prepareScrolling(const QPointF &position) // - check if the content position was moved if (contentDelta != QPointF(0, 0)) { // need to correct all segments - for (int i = 0; i < xSegments.count(); i++) + for (int i = 0; i < xSegments.size(); i++) xSegments[i].startPos -= contentDelta.x(); - for (int i = 0; i < ySegments.count(); i++) + for (int i = 0; i < ySegments.size(); i++) ySegments[i].startPos -= contentDelta.y(); } @@ -1424,7 +1452,8 @@ void QScrollerPrivate::handleDrag(const QPointF &position, qint64 timestamp) if (dx || dy) { bool vertical = (dy > dx); qreal alpha = qreal(vertical ? dx : dy) / qreal(vertical ? dy : dx); - //qScrollerDebug() << "QScroller::handleDrag() -- axis lock:" << alpha << " / " << axisLockThreshold << "- isvertical:" << vertical << "- dx:" << dx << "- dy:" << dy; + qCDebug(lcScroller) << "QScroller::handleDrag() -- axis lock:" << alpha << " / " << sp->axisLockThreshold + << "- isvertical:" << vertical << "- dx:" << dx << "- dy:" << dy; if (alpha <= sp->axisLockThreshold) { if (vertical) deltaPixel.setX(0); @@ -1451,15 +1480,7 @@ void QScrollerPrivate::handleDrag(const QPointF &position, qint64 timestamp) releaseVelocity.setY(0); } -// if (firstDrag) { -// // Do not delay the first drag -// setContentPositionHelper(q->contentPosition() - overshootDistance - deltaPixel); -// dragDistance = QPointF(0, 0); -// } else { dragDistance += deltaPixel; -// } -//qScrollerDebug() << "######################" << deltaPixel << position.y() << lastPosition.y(); - lastPosition = position; lastTimestamp = timestamp; } @@ -1551,7 +1572,7 @@ bool QScrollerPrivate::moveWhileDragging(const QPointF &position, qint64 timesta void QScrollerPrivate::timerEventWhileDragging() { if (dragDistance != QPointF(0, 0)) { - qScrollerDebug() << "QScroller::timerEventWhileDragging() -- dragDistance:" << dragDistance; + qCDebug(lcScroller) << "QScroller::timerEventWhileDragging() -- dragDistance:" << dragDistance; setContentPositionHelperDragging(-dragDistance); dragDistance = QPointF(0, 0); @@ -1596,7 +1617,8 @@ bool QScrollerPrivate::releaseWhileDragging(const QPointF &position, qint64 time QPointF ppm = q->pixelPerMeter(); createScrollingSegments(releaseVelocity, contentPosition + overshootPosition, ppm); - qScrollerDebug() << "QScroller::releaseWhileDragging() -- velocity:" << releaseVelocity << "-- minimum velocity:" << sp->minimumVelocity << "overshoot" << overshootPosition; + qCDebug(lcScroller) << "QScroller::releaseWhileDragging() -- velocity:" << releaseVelocity + << "-- minimum velocity:" << sp->minimumVelocity << "overshoot" << overshootPosition; if (xSegments.isEmpty() && ySegments.isEmpty()) setState(QScroller::Inactive); @@ -1608,7 +1630,7 @@ bool QScrollerPrivate::releaseWhileDragging(const QPointF &position, qint64 time void QScrollerPrivate::timerEventWhileScrolling() { - qScrollerDebug("QScroller::timerEventWhileScrolling()"); + qCDebug(lcScroller) << "QScroller::timerEventWhileScrolling()"; setContentPositionHelperScrolling(); if (xSegments.isEmpty() && ySegments.isEmpty()) @@ -1643,7 +1665,7 @@ void QScrollerPrivate::setState(QScroller::State newstate) if (state == newstate) return; - qScrollerDebug() << q << "QScroller::setState(" << stateName(newstate) << ')'; + qCDebug(lcScroller) << q << "QScroller::setState(" << stateName(newstate) << ')'; switch (newstate) { case QScroller::Inactive: @@ -1721,8 +1743,8 @@ void QScrollerPrivate::setContentPositionHelperDragging(const QPointF &deltaPos) QPointF oldPos = contentPosition + overshootPosition; QPointF newPos = oldPos + deltaPos; - qScrollerDebug() << "QScroller::setContentPositionHelperDragging(" << deltaPos << " [pix])"; - qScrollerDebug() << " --> overshoot:" << overshootPosition << "- old pos:" << oldPos << "- new pos:" << newPos; + qCDebug(lcScroller) << "QScroller::setContentPositionHelperDragging(" << deltaPos << " [pix])"; + qCDebug(lcScroller) << " --> overshoot:" << overshootPosition << "- old pos:" << oldPos << "- new pos:" << newPos; QPointF newClampedPos = clampToRect(newPos, contentPosRange); @@ -1744,8 +1766,9 @@ void QScrollerPrivate::setContentPositionHelperDragging(const QPointF &deltaPos) qreal maxOvershootX = viewportSize.width() * sp->overshootDragDistanceFactor; qreal maxOvershootY = viewportSize.height() * sp->overshootDragDistanceFactor; - qScrollerDebug() << " --> noOs:" << noOvershootX << "drf:" << sp->overshootDragResistanceFactor << "mdf:" << sp->overshootScrollDistanceFactor << "ossP:"<<sp->hOvershootPolicy; - qScrollerDebug() << " --> canOS:" << canOvershootX << "newOS:" << newOvershootX << "maxOS:" << maxOvershootX; + qCDebug(lcScroller) << " --> noOs:" << noOvershootX << "drf:" << sp->overshootDragResistanceFactor + << "mdf:" << sp->overshootScrollDistanceFactor << "ossP:"<<sp->hOvershootPolicy; + qCDebug(lcScroller) << " --> canOS:" << canOvershootX << "newOS:" << newOvershootX << "maxOS:" << maxOvershootX; if (sp->overshootDragResistanceFactor) { newOvershootX *= sp->overshootDragResistanceFactor; @@ -1765,8 +1788,8 @@ void QScrollerPrivate::setContentPositionHelperDragging(const QPointF &deltaPos) sendEvent(target, &se); firstScroll = false; - qScrollerDebug() << " --> new position:" << newClampedPos << "- new overshoot:" << overshootPosition << - "- overshoot x/y?:" << overshootPosition; + qCDebug(lcScroller) << " --> new position:" << newClampedPos << "- new overshoot:" + << overshootPosition << "- overshoot x/y?:" << overshootPosition; } @@ -1806,7 +1829,7 @@ void QScrollerPrivate::setContentPositionHelperScrolling() newPos.setY(nextSegmentPosition(ySegments, now, newPos.y())); // -- set the position and handle overshoot - qScrollerDebug() << "QScroller::setContentPositionHelperScrolling()\n" + qCDebug(lcScroller) << "QScroller::setContentPositionHelperScrolling()\n" " --> overshoot:" << overshootPosition << "- new pos:" << newPos; QPointF newClampedPos = clampToRect(newPos, contentPosRange); @@ -1814,11 +1837,12 @@ void QScrollerPrivate::setContentPositionHelperScrolling() overshootPosition = newPos - newClampedPos; contentPosition = newClampedPos; - QScrollEvent se(contentPosition, overshootPosition, firstScroll ? QScrollEvent::ScrollStarted : QScrollEvent::ScrollUpdated); + QScrollEvent se(contentPosition, overshootPosition, firstScroll ? QScrollEvent::ScrollStarted + : QScrollEvent::ScrollUpdated); sendEvent(target, &se); firstScroll = false; - qScrollerDebug() << " --> new position:" << newClampedPos << "- new overshoot:" << overshootPosition; + qCDebug(lcScroller) << " --> new position:" << newClampedPos << "- new overshoot:" << overshootPosition; } /*! \internal @@ -1949,7 +1973,8 @@ qreal QScrollerPrivate::nextSnapPos(qreal p, int dir, Qt::Orientation orientatio This enum contains the different QScroller states. \value Inactive The scroller is not scrolling and nothing is pressed. - \value Pressed A touch event was received or the mouse button was pressed but the scroll area is currently not dragged. + \value Pressed A touch event was received or the mouse button was pressed + but the scroll area is currently not dragged. \value Dragging The scroll area is currently following the touch point or mouse. \value Scrolling The scroll area is moving on it's own. */ diff --git a/src/widgets/widgets/qabstractbutton.cpp b/src/widgets/widgets/qabstractbutton.cpp index c2f16dc335..bac4a29cff 100644 --- a/src/widgets/widgets/qabstractbutton.cpp +++ b/src/widgets/widgets/qabstractbutton.cpp @@ -180,10 +180,10 @@ QAbstractButton *QAbstractButtonPrivate::queryCheckedButton() const Q_Q(const QAbstractButton); QList<QAbstractButton *> buttonList = queryButtonList(); - if (!autoExclusive || buttonList.count() == 1) // no group + if (!autoExclusive || buttonList.size() == 1) // no group return nullptr; - for (int i = 0; i < buttonList.count(); ++i) { + for (int i = 0; i < buttonList.size(); ++i) { QAbstractButton *b = buttonList.at(i); if (b->d_func()->checked && b != q) return b; @@ -227,7 +227,7 @@ void QAbstractButtonPrivate::moveFocus(int key) QPoint goal = target.center(); uint focus_flag = qt_tab_all_widgets() ? Qt::TabFocus : Qt::StrongFocus; - for (int i = 0; i < buttonList.count(); ++i) { + for (int i = 0; i < buttonList.size(); ++i) { QAbstractButton *button = buttonList.at(i); if (button != f && button->window() == f->window() && button->isEnabled() && !button->isHidden() && (exclusive || (button->focusPolicy() & focus_flag) == focus_flag)) { @@ -310,7 +310,7 @@ void QAbstractButtonPrivate::fixFocusPolicy() return; QList<QAbstractButton *> buttonList = queryButtonList(); - for (int i = 0; i < buttonList.count(); ++i) { + for (int i = 0; i < buttonList.size(); ++i) { QAbstractButton *b = buttonList.at(i); if (!b->isCheckable()) continue; @@ -904,9 +904,6 @@ bool QAbstractButton::event(QEvent *e) case QEvent::HoverEnter: case QEvent::HoverLeave: case QEvent::ContextMenu: -#if QT_CONFIG(wheelevent) - case QEvent::Wheel: -#endif return true; default: break; diff --git a/src/widgets/widgets/qabstractscrollarea.cpp b/src/widgets/widgets/qabstractscrollarea.cpp index 7fd94e6201..d741a70d54 100644 --- a/src/widgets/widgets/qabstractscrollarea.cpp +++ b/src/widgets/widgets/qabstractscrollarea.cpp @@ -295,22 +295,25 @@ void QAbstractScrollAreaPrivate::layoutChildren() void QAbstractScrollAreaPrivate::layoutChildren_helper(bool *needHorizontalScrollbar, bool *needVerticalScrollbar) { Q_Q(QAbstractScrollArea); - bool htransient = hbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, hbar); + QStyleOptionSlider barOpt; + + hbar->initStyleOption(&barOpt); + bool htransient = hbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, &barOpt, hbar); bool needh = *needHorizontalScrollbar || ((hbarpolicy != Qt::ScrollBarAlwaysOff) && ((hbarpolicy == Qt::ScrollBarAlwaysOn && !htransient) || ((hbarpolicy == Qt::ScrollBarAsNeeded || htransient) && hbar->minimum() < hbar->maximum() && !hbar->sizeHint().isEmpty()))); + const int hscrollOverlap = hbar->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarOverlap, &barOpt, hbar); - bool vtransient = vbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, vbar); + vbar->initStyleOption(&barOpt); + bool vtransient = vbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, &barOpt, vbar); bool needv = *needVerticalScrollbar || ((vbarpolicy != Qt::ScrollBarAlwaysOff) && ((vbarpolicy == Qt::ScrollBarAlwaysOn && !vtransient) || ((vbarpolicy == Qt::ScrollBarAsNeeded || vtransient) && vbar->minimum() < vbar->maximum() && !vbar->sizeHint().isEmpty()))); + const int vscrollOverlap = vbar->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarOverlap, &barOpt, vbar); QStyleOption opt(0); opt.initFrom(q); - const int hscrollOverlap = hbar->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarOverlap, &opt, hbar); - const int vscrollOverlap = vbar->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarOverlap, &opt, vbar); - const int hsbExt = hbar->sizeHint().height(); const int vsbExt = vbar->sizeHint().width(); const QPoint extPoint(vsbExt, hsbExt); @@ -368,7 +371,7 @@ void QAbstractScrollAreaPrivate::layoutChildren_helper(bool *needHorizontalScrol #if QT_CONFIG(itemviews) if ((vscrollOverlap > 0 && needv) || (hscrollOverlap > 0 && needh)) { const QList<QHeaderView *> headers = q->findChildren<QHeaderView*>(); - if (headers.count() <= 2) { + if (headers.size() <= 2) { for (const QHeaderView *header : headers) { const QRect geo = header->geometry(); if (header->orientation() == Qt::Vertical && header->isVisible() && QStyle::visualRect(opt.direction, opt.rect, geo).left() <= opt.rect.width() / 2) @@ -1342,10 +1345,14 @@ bool QAbstractScrollAreaPrivate::canStartScrollingAt(const QPoint &startPos) con void QAbstractScrollAreaPrivate::flashScrollBars() { - bool htransient = hbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, hbar); + QStyleOptionSlider opt; + hbar->initStyleOption(&opt); + + bool htransient = hbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, hbar); if ((hbarpolicy != Qt::ScrollBarAlwaysOff) && (hbarpolicy == Qt::ScrollBarAsNeeded || htransient)) hbar->d_func()->flash(); - bool vtransient = vbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, vbar); + vbar->initStyleOption(&opt); + bool vtransient = vbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, vbar); if ((vbarpolicy != Qt::ScrollBarAlwaysOff) && (vbarpolicy == Qt::ScrollBarAsNeeded || vtransient)) vbar->d_func()->flash(); } diff --git a/src/widgets/widgets/qabstractslider.cpp b/src/widgets/widgets/qabstractslider.cpp index 6e44b2d432..4e65fbac88 100644 --- a/src/widgets/widgets/qabstractslider.cpp +++ b/src/widgets/widgets/qabstractslider.cpp @@ -498,18 +498,25 @@ void QAbstractSlider::setValue(int value) value = d->bound(value); if (d->value == value && d->position == value) return; + + // delay signal emission until sliderChanged() has been called + const bool emitValueChanged = (value != d->value); d->value = value; + if (d->position != value) { d->position = value; if (d->pressed) - emit sliderMoved((d->position = value)); + emit sliderMoved(d->position); } #if QT_CONFIG(accessibility) QAccessibleValueChangeEvent event(this, d->value); QAccessible::updateAccessibility(&event); #endif sliderChange(SliderValueChange); - emit valueChanged(value); + + if (emitValueChanged) + emit valueChanged(value); + } /*! diff --git a/src/widgets/widgets/qabstractspinbox.cpp b/src/widgets/widgets/qabstractspinbox.cpp index ff41a72fca..c168b3d990 100644 --- a/src/widgets/widgets/qabstractspinbox.cpp +++ b/src/widgets/widgets/qabstractspinbox.cpp @@ -1952,7 +1952,7 @@ QValidator::State QSpinBoxValidator::validate(QString &input, int &pos) const if (!dptr->prefix.isEmpty() && !input.startsWith(dptr->prefix)) { input.prepend(dptr->prefix); - pos += dptr->prefix.length(); + pos += dptr->prefix.size(); } if (!dptr->suffix.isEmpty() && !input.endsWith(dptr->suffix)) diff --git a/src/widgets/widgets/qbuttongroup.cpp b/src/widgets/widgets/qbuttongroup.cpp index bd0c959396..3a992fed74 100644 --- a/src/widgets/widgets/qbuttongroup.cpp +++ b/src/widgets/widgets/qbuttongroup.cpp @@ -14,7 +14,7 @@ void QButtonGroupPrivate::detectCheckedButton() checkedButton = nullptr; if (exclusive) return; - for (int i = 0; i < buttonList.count(); i++) { + for (int i = 0; i < buttonList.size(); i++) { if (buttonList.at(i) != previous && buttonList.at(i)->isChecked()) { checkedButton = buttonList.at(i); return; @@ -82,7 +82,7 @@ QButtonGroup::QButtonGroup(QObject *parent) QButtonGroup::~QButtonGroup() { Q_D(QButtonGroup); - for (int i = 0; i < d->buttonList.count(); ++i) + for (int i = 0; i < d->buttonList.size(); ++i) d->buttonList.at(i)->d_func()->group = nullptr; } diff --git a/src/widgets/widgets/qcalendarwidget.cpp b/src/widgets/widgets/qcalendarwidget.cpp index 42ef8c4a35..4d3360226f 100644 --- a/src/widgets/widgets/qcalendarwidget.cpp +++ b/src/widgets/widgets/qcalendarwidget.cpp @@ -72,7 +72,7 @@ QString QCalendarDateSectionValidator::highlightString(const QString &str, int p { if (pos == 0) return "<b>"_L1 + str + "</b>"_L1; - int startPos = str.length() - pos; + int startPos = str.size() - pos; return QStringView{str}.mid(0, startPos) + "<b>"_L1 + QStringView{str}.mid(startPos, pos) + "</b>"_L1; } @@ -728,7 +728,7 @@ bool QCalendarTextNavigator::eventFilter(QObject *o, QEvent *e) if (m_widget) { if (e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease) { QKeyEvent* ke = (QKeyEvent*)e; - if ((ke->text().length() > 0 && ke->text().at(0).isPrint()) || m_dateFrame) { + if ((ke->text().size() > 0 && ke->text().at(0).isPrint()) || m_dateFrame) { if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter || ke->key() == Qt::Key_Select) { applyDate(); emit editingFinished(); diff --git a/src/widgets/widgets/qcombobox.cpp b/src/widgets/widgets/qcombobox.cpp index 9caac239f9..8a5ba769a8 100644 --- a/src/widgets/widgets/qcombobox.cpp +++ b/src/widgets/widgets/qcombobox.cpp @@ -58,7 +58,8 @@ QComboBoxPrivate::QComboBoxPrivate() shownOnce(false), duplicatesEnabled(false), frame(true), - inserting(false) + inserting(false), + hidingPopup(false) { } @@ -735,8 +736,8 @@ bool QComboBoxPrivateContainer::eventFilter(QObject *o, QEvent *e) return true; default: #if QT_CONFIG(shortcut) - if (keyEvent->matches(QKeySequence::Cancel)) { - combo->hidePopup(); + if (keyEvent->matches(QKeySequence::Cancel) && isVisible()) { + keyEvent->accept(); return true; } #endif @@ -2297,7 +2298,7 @@ void QComboBox::insertItems(int index, const QStringList &list) if (list.isEmpty()) return; index = qBound(0, index, count()); - int insertCount = qMin(d->maxCount - index, list.count()); + int insertCount = qMin(d->maxCount - index, list.size()); if (insertCount <= 0) return; // For the common case where we are using the built in QStandardItemModel @@ -2805,6 +2806,13 @@ void QComboBox::showPopup() void QComboBox::hidePopup() { Q_D(QComboBox); + if (d->hidingPopup) + return; + d->hidingPopup = true; + // can't use QBoolBlocker on a bitfield + auto resetHidingPopup = qScopeGuard([d]{ + d->hidingPopup = false; + }); if (d->container && d->container->isVisible()) { #if QT_CONFIG(effects) QSignalBlocker modelBlocker(d->model); @@ -2829,30 +2837,11 @@ void QComboBox::hidePopup() } } - // Fade out. - bool needFade = style()->styleHint(QStyle::SH_Menu_FadeOutOnHide); - bool didFade = false; - if (needFade) { -#if defined(Q_OS_MAC) - QPlatformNativeInterface *platformNativeInterface = QGuiApplication::platformNativeInterface(); - int at = platformNativeInterface->metaObject()->indexOfMethod("fadeWindow()"); - if (at != -1) { - QMetaMethod windowFade = platformNativeInterface->metaObject()->method(at); - windowFade.invoke(platformNativeInterface, Q_ARG(QWindow *, d->container->windowHandle())); - didFade = true; - } - -#endif // Q_OS_MAC - // Other platform implementations welcome :-) - } containerBlocker.unblock(); viewBlocker.unblock(); modelBlocker.unblock(); - - if (!didFade) #endif // QT_CONFIG(effects) - // Fade should implicitly hide as well ;-) - d->container->hide(); + d->container->hide(); } #ifdef QT_KEYPAD_NAVIGATION if (QApplicationPrivate::keypadNavigationEnabled() && isEditable() && hasFocus()) @@ -3223,6 +3212,8 @@ void QComboBox::keyPressEvent(QKeyEvent *e) return; } break; + case Qt::Key_Enter: + case Qt::Key_Return: case Qt::Key_Escape: if (!d->lineEdit) e->ignore(); @@ -3243,6 +3234,11 @@ void QComboBox::keyPressEvent(QKeyEvent *e) break; #endif default: + if (d->container && d->container->isVisible() && e->matches(QKeySequence::Cancel)) { + hidePopup(); + e->accept(); + } + if (!d->lineEdit) { if (!e->text().isEmpty()) d->keyboardSearchString(e->text()); diff --git a/src/widgets/widgets/qcombobox_p.h b/src/widgets/widgets/qcombobox_p.h index d725624d6d..a26f3a34d4 100644 --- a/src/widgets/widgets/qcombobox_p.h +++ b/src/widgets/widgets/qcombobox_p.h @@ -395,6 +395,7 @@ public: bool duplicatesEnabled : 1; bool frame : 1; bool inserting : 1; + bool hidingPopup : 1; }; QT_END_NAMESPACE diff --git a/src/widgets/widgets/qdatetimeedit.cpp b/src/widgets/widgets/qdatetimeedit.cpp index 5e61a87fd7..e7b644a67b 100644 --- a/src/widgets/widgets/qdatetimeedit.cpp +++ b/src/widgets/widgets/qdatetimeedit.cpp @@ -1597,7 +1597,7 @@ QTimeEdit::QTimeEdit(QWidget *parent) */ QTimeEdit::QTimeEdit(QTime time, QWidget *parent) - : QDateTimeEdit(time, QMetaType::QTime, parent) + : QDateTimeEdit(time.isValid() ? time : QDATETIMEEDIT_TIME_MIN, QMetaType::QTime, parent) { connect(this, &QTimeEdit::timeChanged, this, &QTimeEdit::userTimeChanged); } @@ -1667,7 +1667,7 @@ QDateEdit::QDateEdit(QWidget *parent) */ QDateEdit::QDateEdit(QDate date, QWidget *parent) - : QDateTimeEdit(date, QMetaType::QDate, parent) + : QDateTimeEdit(date.isValid() ? date : QDATETIMEEDIT_DATE_INITIAL, QMetaType::QDate, parent) { connect(this, &QDateEdit::dateChanged, this, &QDateEdit::userDateChanged); } @@ -1830,7 +1830,7 @@ int QDateTimeEditPrivate::sectionAt(int pos) const const int textSize = text.size(); if (textSize - pos < separators.last().size() + 1) { if (separators.last().size() == 0) { - return sectionNodes.count() - 1; + return sectionNodes.size() - 1; } return (pos == textSize ? LastSectionIndex : NoSectionIndex); } @@ -2480,7 +2480,7 @@ void QDateTimeEditPrivate::init(const QVariant &var) Q_Q(QDateTimeEdit); switch (var.userType()) { case QMetaType::QDate: - value = var.toDate().startOfDay(); + value = var.toDate().startOfDay(spec); updateTimeSpec(); q->setDisplayFormat(defaultDateFormat); if (sectionNodes.isEmpty()) // ### safeguard for broken locale @@ -2494,7 +2494,7 @@ void QDateTimeEditPrivate::init(const QVariant &var) q->setDisplayFormat("dd/MM/yyyy hh:mm:ss"_L1); break; case QMetaType::QTime: - value = QDateTime(QDATETIMEEDIT_DATE_INITIAL, var.toTime()); + value = QDateTime(QDATETIMEEDIT_DATE_INITIAL, var.toTime(), spec); updateTimeSpec(); q->setDisplayFormat(defaultTimeFormat); if (sectionNodes.isEmpty()) // ### safeguard for broken locale diff --git a/src/widgets/widgets/qdialogbuttonbox.cpp b/src/widgets/widgets/qdialogbuttonbox.cpp index 8d874aaa03..1f8bdc0f94 100644 --- a/src/widgets/widgets/qdialogbuttonbox.cpp +++ b/src/widgets/widgets/qdialogbuttonbox.cpp @@ -185,8 +185,8 @@ void QDialogButtonBoxPrivate::resetLayout() void QDialogButtonBoxPrivate::addButtonsToLayout(const QList<QAbstractButton *> &buttonList, bool reverse) { - int start = reverse ? buttonList.count() - 1 : 0; - int end = reverse ? -1 : buttonList.count(); + int start = reverse ? buttonList.size() - 1 : 0; + int end = reverse ? -1 : buttonList.size(); int step = reverse ? -1 : 1; for (int i = start; i != end; i += step) { @@ -636,7 +636,7 @@ void QDialogButtonBox::clear() d->standardButtonHash.clear(); for (int i = 0; i < NRoles; ++i) { QList<QAbstractButton *> &list = d->buttonLists[i]; - while (list.count()) { + while (list.size()) { QAbstractButton *button = list.takeAt(0); QObject::disconnect(button, SIGNAL(destroyed()), this, SLOT(_q_handleButtonDestroyed())); delete button; @@ -655,7 +655,7 @@ QList<QAbstractButton *> QDialogButtonBox::buttons() const QList<QAbstractButton *> finalList; for (int i = 0; i < NRoles; ++i) { const QList<QAbstractButton *> &list = d->buttonLists[i]; - for (int j = 0; j < list.count(); ++j) + for (int j = 0; j < list.size(); ++j) finalList.append(list.at(j)); } return finalList; @@ -672,7 +672,7 @@ QDialogButtonBox::ButtonRole QDialogButtonBox::buttonRole(QAbstractButton *butto Q_D(const QDialogButtonBox); for (int i = 0; i < NRoles; ++i) { const QList<QAbstractButton *> &list = d->buttonLists[i]; - for (int j = 0; j < list.count(); ++j) { + for (int j = 0; j < list.size(); ++j) { if (list.at(j) == button) return ButtonRole(i); } @@ -696,7 +696,7 @@ void QDialogButtonBox::removeButton(QAbstractButton *button) d->standardButtonHash.remove(reinterpret_cast<QPushButton *>(button)); for (int i = 0; i < NRoles; ++i) { QList<QAbstractButton *> &list = d->buttonLists[i]; - for (int j = 0; j < list.count(); ++j) { + for (int j = 0; j < list.size(); ++j) { if (list.at(j) == button) { list.takeAt(j); if (!d->internalRemove) { diff --git a/src/widgets/widgets/qdockarealayout.cpp b/src/widgets/widgets/qdockarealayout.cpp index cec1d1bc14..2e3602e47a 100644 --- a/src/widgets/widgets/qdockarealayout.cpp +++ b/src/widgets/widgets/qdockarealayout.cpp @@ -91,7 +91,7 @@ bool QDockAreaLayoutItem::skip() const return widgetItem->isEmpty(); if (subinfo != nullptr) { - for (int i = 0; i < subinfo->item_list.count(); ++i) { + for (int i = 0; i < subinfo->item_list.size(); ++i) { if (!subinfo->item_list.at(i).skip()) return false; } @@ -852,7 +852,7 @@ static int separatorMoveHelper(QList<QLayoutStruct> &list, int index, int delta, delta = growlimit; int d = 0; - for (int i = index + 1; d < delta && i < list.count(); ++i) + for (int i = index + 1; d < delta && i < list.size(); ++i) d += shrink(list[i], delta - d); delta = d; d = 0; @@ -860,7 +860,7 @@ static int separatorMoveHelper(QList<QLayoutStruct> &list, int index, int delta, d += grow(list[i], delta - d); } else if (delta < 0) { int growlimit = 0; - for (int i = index + 1; i < list.count(); ++i) { + for (int i = index + 1; i < list.size(); ++i) { const QLayoutStruct &ls = list.at(i); if (ls.empty) continue; @@ -878,7 +878,7 @@ static int separatorMoveHelper(QList<QLayoutStruct> &list, int index, int delta, d += shrink(list[i], -delta - d); delta = -d; d = 0; - for (int i = index + 1; d < -delta && i < list.count(); ++i) + for (int i = index + 1; d < -delta && i < list.size(); ++i) d += grow(list[i], -delta - d); } @@ -949,12 +949,12 @@ void QDockAreaLayoutInfo::unnest(int index) QDockAreaLayoutItem &item = item_list[index]; if (item.subinfo == nullptr) return; - if (item.subinfo->item_list.count() > 1) + if (item.subinfo->item_list.size() > 1) return; - if (item.subinfo->item_list.count() == 0) { + if (item.subinfo->item_list.size() == 0) { item_list.removeAt(index); - } else if (item.subinfo->item_list.count() == 1) { + } else if (item.subinfo->item_list.size() == 1) { QDockAreaLayoutItem &child = item.subinfo->item_list.first(); if (child.widgetItem != nullptr) { item.widgetItem = child.widgetItem; @@ -974,7 +974,7 @@ void QDockAreaLayoutInfo::remove(const QList<int> &path) { Q_ASSERT(!path.isEmpty()); - if (path.count() > 1) { + if (path.size() > 1) { const int index = path.first(); QDockAreaLayoutItem &item = item_list[index]; Q_ASSERT(item.subinfo != nullptr); @@ -994,7 +994,7 @@ QLayoutItem *QDockAreaLayoutInfo::plug(const QList<int> &path) if (index < 0) index = -index - 1; - if (path.count() > 1) { + if (path.size() > 1) { QDockAreaLayoutItem &item = item_list[index]; Q_ASSERT(item.subinfo != nullptr); return item.subinfo->plug(path.mid(1)); @@ -1013,7 +1013,7 @@ QLayoutItem *QDockAreaLayoutInfo::unplug(const QList<int> &path) Q_ASSERT(!path.isEmpty()); const int index = path.first(); - if (path.count() > 1) { + if (path.size() > 1) { QDockAreaLayoutItem &item = item_list[index]; Q_ASSERT(item.subinfo != nullptr); return item.subinfo->unplug(path.mid(1)); @@ -1103,7 +1103,7 @@ bool QDockAreaLayoutInfo::insertGap(const QList<int> &path, QLayoutItem *dockWid // dump(qDebug() << "insertGap() before:" << index << tabIndex, *this, QString()); - if (path.count() > 1) { + if (path.size() > 1) { QDockAreaLayoutItem &item = item_list[index]; if (item.subinfo == nullptr @@ -1185,7 +1185,7 @@ bool QDockAreaLayoutInfo::insertGap(const QList<int> &path, QLayoutItem *dockWid break; } } else { - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { const QDockAreaLayoutItem &item = item_list.at(i); if (item.skip()) continue; @@ -1224,7 +1224,7 @@ bool QDockAreaLayoutInfo::insertGap(const QList<int> &path, QLayoutItem *dockWid QDockAreaLayoutInfo *QDockAreaLayoutInfo::info(QWidget *widget) { - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { const QDockAreaLayoutItem &item = item_list.at(i); if (item.skip()) continue; @@ -1251,9 +1251,9 @@ QDockAreaLayoutInfo *QDockAreaLayoutInfo::info(const QList<int> &path) int index = path.first(); if (index < 0) index = -index - 1; - if (index >= item_list.count()) + if (index >= item_list.size()) return this; - if (path.count() == 1 || item_list[index].subinfo == nullptr) + if (path.size() == 1 || item_list[index].subinfo == nullptr) return this; return item_list[index].subinfo->info(path.mid(1)); } @@ -1308,7 +1308,7 @@ QRect QDockAreaLayoutInfo::itemRect(const QList<int> &path) const Q_ASSERT(!path.isEmpty()); const int index = path.first(); - if (path.count() > 1) { + if (path.size() > 1) { const QDockAreaLayoutItem &item = item_list.at(index); Q_ASSERT(item.subinfo != nullptr); return item.subinfo->itemRect(path.mid(1)); @@ -1341,7 +1341,7 @@ QRect QDockAreaLayoutInfo::separatorRect(const QList<int> &path) const Q_ASSERT(!path.isEmpty()); const int index = path.first(); - if (path.count() > 1) { + if (path.size() > 1) { const QDockAreaLayoutItem &item = item_list.at(index); Q_ASSERT(item.subinfo != nullptr); return item.subinfo->separatorRect(path.mid(1)); @@ -1566,7 +1566,7 @@ QRegion QDockAreaLayoutInfo::separatorRegion() const return result; #endif - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { const QDockAreaLayoutItem &item = item_list.at(i); if (item.skip()) @@ -1596,7 +1596,7 @@ void QDockAreaLayoutInfo::paintSeparators(QPainter *p, QWidget *widget, return; #endif - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { const QDockAreaLayoutItem &item = item_list.at(i); if (item.skip()) @@ -1681,7 +1681,7 @@ QDockAreaLayoutItem &QDockAreaLayoutInfo::item(const QList<int> &path) { Q_ASSERT(!path.isEmpty()); const int index = path.first(); - if (path.count() > 1) { + if (path.size() > 1) { const QDockAreaLayoutItem &item = item_list[index]; Q_ASSERT(item.subinfo != nullptr); return item.subinfo->item(path.mid(1)); @@ -1691,7 +1691,7 @@ QDockAreaLayoutItem &QDockAreaLayoutInfo::item(const QList<int> &path) QLayoutItem *QDockAreaLayoutInfo::itemAt(int *x, int index) const { - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { const QDockAreaLayoutItem &item = item_list.at(i); if (item.placeHolderItem != nullptr) continue; @@ -1708,7 +1708,7 @@ QLayoutItem *QDockAreaLayoutInfo::itemAt(int *x, int index) const QLayoutItem *QDockAreaLayoutInfo::takeAt(int *x, int index) { - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { QDockAreaLayoutItem &item = item_list[i]; if (item.placeHolderItem != nullptr) continue; @@ -1733,7 +1733,7 @@ QLayoutItem *QDockAreaLayoutInfo::takeAt(int *x, int index) void QDockAreaLayoutInfo::deleteAllLayoutItems() { - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { QDockAreaLayoutItem &item= item_list[i]; if (item.subinfo) { item.subinfo->deleteAllLayoutItems(); @@ -1753,7 +1753,7 @@ void QDockAreaLayoutInfo::saveState(QDataStream &stream) const // write the index in item_list of the widget that's currently on top. quintptr id = currentTabId(); int index = -1; - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { if (tabId(item_list.at(i)) == id) { index = i; break; @@ -1766,9 +1766,9 @@ void QDockAreaLayoutInfo::saveState(QDataStream &stream) const stream << (uchar) SequenceMarker; } - stream << (uchar) o << int(item_list.count()); + stream << (uchar) o << int(item_list.size()); - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { const QDockAreaLayoutItem &item = item_list.at(i); if (item.widgetItem != nullptr) { stream << (uchar) WidgetMarker; @@ -1864,7 +1864,7 @@ bool QDockAreaLayoutInfo::restoreState(QDataStream &stream, QList<QDockWidget*> } QDockWidget *widget = nullptr; - for (int j = 0; j < widgets.count(); ++j) { + for (int j = 0; j < widgets.size(); ++j) { if (widgets.at(j)->objectName() == name) { widget = widgets.takeAt(j); break; @@ -1950,7 +1950,7 @@ bool QDockAreaLayoutInfo::restoreState(QDataStream &stream, QList<QDockWidget*> } #if QT_CONFIG(tabbar) - if (!testing && tabbed && index >= 0 && index < item_list.count()) { + if (!testing && tabbed && index >= 0 && index < item_list.size()) { updateTabBar(); setCurrentTabId(tabId(item_list.at(index))); } @@ -1970,7 +1970,7 @@ void QDockAreaLayoutInfo::updateSeparatorWidgets() const } int j = 0; - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { const QDockAreaLayoutItem &item = item_list.at(i); if (item.skip()) @@ -2022,7 +2022,7 @@ void QDockAreaLayoutInfo::reparentWidgets(QWidget *parent) if (tabBar) tabBar->setParent(parent); - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { const QDockAreaLayoutItem &item = item_list.at(i); if (item.flags & QDockAreaLayoutItem::GapItem) continue; @@ -2062,7 +2062,7 @@ bool QDockAreaLayoutInfo::updateTabBar() const const quintptr oldCurrentId = currentTabId(); int tab_idx = 0; - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { const QDockAreaLayoutItem &item = item_list.at(i); if (item.skip()) continue; @@ -2127,7 +2127,7 @@ void QDockAreaLayoutInfo::setTabBarShape(int shape) if (tabBar != nullptr) tabBar->setShape(static_cast<QTabBar::Shape>(shape)); - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { QDockAreaLayoutItem &item = item_list[i]; if (item.subinfo != nullptr) item.subinfo->setTabBarShape(shape); @@ -2159,7 +2159,7 @@ QSet<QTabBar*> QDockAreaLayoutInfo::usedTabBars() const result.insert(tabBar); } - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { const QDockAreaLayoutItem &item = item_list.at(i); if (item.subinfo != nullptr) result += item.subinfo->usedTabBars(); @@ -2173,13 +2173,13 @@ QSet<QTabBar*> QDockAreaLayoutInfo::usedTabBars() const QSet<QWidget*> QDockAreaLayoutInfo::usedSeparatorWidgets() const { QSet<QWidget*> result; - const int numSeparatorWidgets = separatorWidgets.count(); + const int numSeparatorWidgets = separatorWidgets.size(); result.reserve(numSeparatorWidgets); for (int i = 0; i < numSeparatorWidgets; ++i) result << separatorWidgets.at(i); - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { const QDockAreaLayoutItem &item = item_list.at(i); if (item.subinfo != nullptr) result += item.subinfo->usedSeparatorWidgets(); @@ -2226,7 +2226,7 @@ int QDockAreaLayoutInfo::tabIndexToListIndex(int tabIndex) const { Q_ASSERT(tabbed && tabBar); quintptr data = qvariant_cast<quintptr>(tabBar->tabData(tabIndex)); - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { if (tabId(item_list.at(i)) == data) return i; } @@ -2490,7 +2490,7 @@ QDockAreaLayoutInfo *QDockAreaLayout::info(const QList<int> &path) const int index = path.first(); Q_ASSERT(index >= 0 && index < QInternal::DockCount); - if (path.count() == 1) + if (path.size() == 1) return &docks[index]; return docks[index].info(path.mid(1)); @@ -2545,7 +2545,7 @@ QRect QDockAreaLayout::separatorRect(const QList<int> &path) const const int index = path.first(); Q_ASSERT(index >= 0 && index < QInternal::DockCount); - if (path.count() == 1) + if (path.size() == 1) return separatorRect(index); else return docks[index].separatorRect(path.mid(1)); @@ -3043,7 +3043,7 @@ void QDockAreaLayout::addDockWidget(QInternal::DockPosition pos, QDockWidget *do { QLayoutItem *dockWidgetItem = new QDockWidgetItem(dockWidget); QDockAreaLayoutInfo &info = docks[pos]; - if (orientation == info.o || info.item_list.count() <= 1) { + if (orientation == info.o || info.item_list.size() <= 1) { // empty dock areas, or dock areas containing exactly one widget can have their orientation // switched. info.o = orientation; @@ -3089,11 +3089,11 @@ void QDockAreaLayout::tabifyDockWidget(QDockWidget *first, QDockWidget *second) void QDockAreaLayout::resizeDocks(const QList<QDockWidget *> &docks, const QList<int> &sizes, Qt::Orientation o) { - if (Q_UNLIKELY(docks.count() != sizes.count())) { + if (Q_UNLIKELY(docks.size() != sizes.size())) { qWarning("QMainWidget::resizeDocks: size of the lists are not the same"); return; } - int count = docks.count(); + int count = docks.size(); fallbackToSizeHints = false; for (int i = 0; i < count; ++i) { QList<int> path = indexOf(docks[i]); @@ -3113,7 +3113,7 @@ void QDockAreaLayout::resizeDocks(const QList<QDockWidget *> &docks, if (!info->tabbed && info->o == o) { info->item_list[path.constLast()].size = size; int totalSize = 0; - for (const QDockAreaLayoutItem &item : qAsConst(info->item_list)) { + for (const QDockAreaLayoutItem &item : std::as_const(info->item_list)) { if (!item.skip()) { if (totalSize != 0) totalSize += sep; @@ -3206,7 +3206,7 @@ int QDockAreaLayout::separatorMove(const QList<int> &separator, const QPoint &or int delta = 0; int index = separator.last(); - if (separator.count() > 1) { + if (separator.size() > 1) { QDockAreaLayoutInfo *info = this->info(separator); delta = pick(info->o, dest - origin); if (delta != 0) @@ -3347,7 +3347,7 @@ QSet<QTabBar*> QDockAreaLayout::usedTabBars() const QSet<QWidget*> QDockAreaLayout::usedSeparatorWidgets() const { QSet<QWidget*> result; - const int numSeparators = separatorWidgets.count(); + const int numSeparators = separatorWidgets.size(); result.reserve(numSeparators); for (int i = 0; i < numSeparators; ++i) result << separatorWidgets.at(i); @@ -3365,7 +3365,7 @@ QRect QDockAreaLayout::gapRect(const QList<int> &path) const if (info == nullptr) return QRect(); int index = path.last(); - if (index < 0 || index >= info->item_list.count()) + if (index < 0 || index >= info->item_list.size()) return QRect(); return info->itemRect(index, true); } diff --git a/src/widgets/widgets/qdockwidget.cpp b/src/widgets/widgets/qdockwidget.cpp index ec5e4d51d5..67bb099446 100644 --- a/src/widgets/widgets/qdockwidget.cpp +++ b/src/widgets/widgets/qdockwidget.cpp @@ -277,7 +277,7 @@ void QDockWidgetLayout::addItem(QLayoutItem*) QLayoutItem *QDockWidgetLayout::itemAt(int index) const { int cnt = 0; - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { QLayoutItem *item = item_list.at(i); if (item == nullptr) continue; @@ -290,7 +290,7 @@ QLayoutItem *QDockWidgetLayout::itemAt(int index) const QLayoutItem *QDockWidgetLayout::takeAt(int index) { int j = 0; - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { QLayoutItem *item = item_list.at(i); if (item == nullptr) continue; @@ -307,7 +307,7 @@ QLayoutItem *QDockWidgetLayout::takeAt(int index) int QDockWidgetLayout::count() const { int result = 0; - for (int i = 0; i < item_list.count(); ++i) { + for (int i = 0; i < item_list.size(); ++i) { if (item_list.at(i)) ++result; } @@ -754,7 +754,7 @@ void QDockWidgetPrivate::initDrag(const QPoint &pos, bool nca) state = new QDockWidgetPrivate::DragState; state->pressPos = pos; state->globalPressPos = q->mapToGlobal(pos); - state->widgetInitialPos = q->pos(); + state->widgetInitialPos = q->isFloating() ? q->pos() : q->mapToGlobal(QPoint(0, 0)); state->dragging = false; state->widgetItem = nullptr; state->ownWidgetItem = false; @@ -1006,19 +1006,25 @@ bool QDockWidgetPrivate::mouseMoveEvent(QMouseEvent *event) - windowMarginOffset; } else { // Fallback in the unlikely case that source and target screens could not be established - qCWarning(lcQpaDockWidgets) + qCDebug(lcQpaDockWidgets) << "QDockWidget failed to find relevant screen info. screenFrom:" << screenFrom << "screenTo:" << screenTo << " wdgScreen:" << wdgScreen << "orgWdgScreen" << orgWdgScreen; pos = event->globalPosition().toPoint() - state->pressPos - windowMarginOffset; } + // If the newly floating dock widget has got a native title bar, + // offset the position by the native title bar's height or width + const int dx = q->geometry().x() - q->x(); + const int dy = q->geometry().y() - q->y(); + pos.rx() += dx; + pos.ry() += dy; + QDockWidgetGroupWindow *floatingTab = qobject_cast<QDockWidgetGroupWindow*>(parent); if (floatingTab && !q->isFloating()) floatingTab->move(pos); else q->move(pos); - if (state && !state->ctrlDrag) mwlayout->hover(state->widgetItem, event->globalPosition().toPoint()); @@ -1079,14 +1085,14 @@ void QDockWidgetPrivate::nonClientAreaMouseEvent(QMouseEvent *event) if (state == nullptr || !state->dragging) break; -#ifndef Q_OS_MAC +#if !defined(Q_OS_MAC) && !defined(Q_OS_WASM) if (state->nca) { endDrag(); } #endif break; case QEvent::NonClientAreaMouseButtonRelease: -#ifdef Q_OS_MAC +#if defined(Q_OS_MAC) || defined(Q_OS_WASM) if (state) endDrag(); #endif @@ -1571,7 +1577,7 @@ bool QDockWidget::event(QEvent *event) bool onTop = false; if (win != nullptr) { const QObjectList &siblings = win->children(); - onTop = siblings.count() > 0 && siblings.last() == (QObject*)this; + onTop = siblings.size() > 0 && siblings.last() == (QObject*)this; } #if QT_CONFIG(tabbar) if (!isFloating() && layout != nullptr && onTop) diff --git a/src/widgets/widgets/qfontcombobox.cpp b/src/widgets/widgets/qfontcombobox.cpp index c4239e70ca..a7f31995e1 100644 --- a/src/widgets/widgets/qfontcombobox.cpp +++ b/src/widgets/widgets/qfontcombobox.cpp @@ -132,13 +132,13 @@ static QFontDatabase::WritingSystem writingSystemForFont(const QFont &font, bool return system; } - if (writingSystems.count() == 1 && system > QFontDatabase::Cyrillic) + if (writingSystems.size() == 1 && system > QFontDatabase::Cyrillic) return system; - if (writingSystems.count() <= 2 && system > QFontDatabase::Armenian && system < QFontDatabase::Vietnamese) + if (writingSystems.size() <= 2 && system > QFontDatabase::Armenian && system < QFontDatabase::Vietnamese) return system; - if (writingSystems.count() <= 5 && system >= QFontDatabase::SimplifiedChinese && system <= QFontDatabase::Korean) + if (writingSystems.size() <= 5 && system >= QFontDatabase::SimplifiedChinese && system <= QFontDatabase::Korean) return system; return QFontDatabase::Any; @@ -317,7 +317,7 @@ void QFontComboBoxPrivate::_q_updateModel() } result += list.at(i); if (list.at(i) == fi.family() || list.at(i).startsWith(fi.family() + " ["_L1)) - offset = result.count() - 1; + offset = result.size() - 1; } list = result; diff --git a/src/widgets/widgets/qframe.cpp b/src/widgets/widgets/qframe.cpp index 6f4310facb..db8dc20be2 100644 --- a/src/widgets/widgets/qframe.cpp +++ b/src/widgets/widgets/qframe.cpp @@ -428,9 +428,9 @@ int QFrame::frameWidth() const \brief the frame's rectangle The frame's rectangle is the rectangle the frame is drawn in. By - default, this is the entire widget. Setting the rectangle does - does \e not cause a widget update. The frame rectangle is - automatically adjusted when the widget changes size. + default, this is the entire widget. Setting the rectangle \e doesn't + cause a widget update. The frame rectangle is automatically adjusted + when the widget changes size. If you set the rectangle to a null rectangle (for example, QRect(0, 0, 0, 0)), then the resulting frame rectangle is diff --git a/src/widgets/widgets/qlcdnumber.cpp b/src/widgets/widgets/qlcdnumber.cpp index 6f49b831ad..eef2685569 100644 --- a/src/widgets/widgets/qlcdnumber.cpp +++ b/src/widgets/widgets/qlcdnumber.cpp @@ -149,7 +149,7 @@ static QString int2string(int num, int base, int ndigits, bool *oflow) break; } if (negative) { - for (int i=0; i<(int)s.length(); i++) { + for (int i=0; i<(int)s.size(); i++) { if (s[i] != u' ') { if (i != 0) { s[i-1] = u'-'; @@ -161,7 +161,7 @@ static QString int2string(int num, int base, int ndigits, bool *oflow) } } if (oflow) - *oflow = (int)s.length() > ndigits; + *oflow = (int)s.size() > ndigits; return s; } @@ -186,10 +186,10 @@ static QString double2string(double num, int base, int ndigits, bool *oflow) s[i] = u' '; s[i+1] = u'e'; } - } while (nd-- && (int)s.length() > ndigits); + } while (nd-- && (int)s.size() > ndigits); } if (oflow) - *oflow = (int)s.length() > ndigits; + *oflow = (int)s.size() > ndigits; return s; } @@ -679,7 +679,7 @@ void QLCDNumberPrivate::internalSetString(const QString& s) Q_Q(QLCDNumber); QString buffer(ndigits, QChar()); int i; - int len = s.length(); + int len = s.size(); QBitArray newPoints(ndigits); if (!smallPoint) { diff --git a/src/widgets/widgets/qlineedit.cpp b/src/widgets/widgets/qlineedit.cpp index b87d7e09cc..c38f3db7a1 100644 --- a/src/widgets/widgets/qlineedit.cpp +++ b/src/widgets/widgets/qlineedit.cpp @@ -1611,7 +1611,7 @@ void QLineEdit::mouseDoubleClickEvent(QMouseEvent* e) if (d->control->composeMode()) { int preeditPos = d->control->cursor(); int posInPreedit = position - d->control->cursor(); - int preeditLength = d->control->preeditAreaText().length(); + int preeditLength = d->control->preeditAreaText().size(); bool positionOnPreedit = false; if (posInPreedit >= 0 && posInPreedit <= preeditLength) @@ -2123,13 +2123,13 @@ void QLineEdit::dropEvent(QDropEvent* e) if (e->source() == this) { if (e->dropAction() == Qt::MoveAction) { if (selStart > oldSelStart && selStart <= oldSelEnd) - setSelection(oldSelStart, str.length()); + setSelection(oldSelStart, str.size()); else if (selStart > oldSelEnd) - setSelection(selStart - str.length(), str.length()); + setSelection(selStart - str.size(), str.size()); else - setSelection(selStart, str.length()); + setSelection(selStart, str.size()); } else { - setSelection(selStart, str.length()); + setSelection(selStart, str.size()); } } } else { diff --git a/src/widgets/widgets/qlineedit_p.cpp b/src/widgets/widgets/qlineedit_p.cpp index cdfe6df7f6..e846600149 100644 --- a/src/widgets/widgets/qlineedit_p.cpp +++ b/src/widgets/widgets/qlineedit_p.cpp @@ -279,7 +279,7 @@ bool QLineEditPrivate::sendMouseEventToInputContext( QMouseEvent *e ) if ( control->composeMode() ) { int tmp_cursor = xToPos(e->position().toPoint().x()); int mousePos = tmp_cursor - control->cursor(); - if ( mousePos < 0 || mousePos > control->preeditAreaText().length() ) + if ( mousePos < 0 || mousePos > control->preeditAreaText().size() ) mousePos = -1; if (mousePos >= 0) { diff --git a/src/widgets/widgets/qmainwindow.cpp b/src/widgets/widgets/qmainwindow.cpp index 73ca584c7f..256e97396b 100644 --- a/src/widgets/widgets/qmainwindow.cpp +++ b/src/widgets/widgets/qmainwindow.cpp @@ -1124,7 +1124,7 @@ QList<QDockWidget*> QMainWindow::tabifiedDockWidgets(QDockWidget *dockwidget) co QList<QDockWidget*> ret; const QDockAreaLayoutInfo *info = d_func()->layout->layoutState.dockAreaLayout.info(dockwidget); if (info && info->tabbed && info->tabBar) { - for(int i = 0; i < info->item_list.count(); ++i) { + for(int i = 0; i < info->item_list.size(); ++i) { const QDockAreaLayoutItem &item = info->item_list.at(i); if (item.widgetItem) { if (QDockWidget *dock = qobject_cast<QDockWidget*>(item.widgetItem->widget())) { diff --git a/src/widgets/widgets/qmainwindowlayout.cpp b/src/widgets/widgets/qmainwindowlayout.cpp index 10732aecbe..08abcd1ada 100644 --- a/src/widgets/widgets/qmainwindowlayout.cpp +++ b/src/widgets/widgets/qmainwindowlayout.cpp @@ -106,7 +106,7 @@ static void dumpLayout(QTextStream &qout, const QDockAreaLayoutInfo &layout, QSt indent += " "_L1; - for (int i = 0; i < layout.item_list.count(); ++i) { + for (int i = 0; i < layout.item_list.size(); ++i) { qout << indent << "Item: " << i << '\n'; dumpLayout(qout, layout.item_list.at(i), indent + " "_L1); } @@ -366,7 +366,7 @@ QDockWidget *QDockWidgetGroupWindow::activeTabbedDockWidget() const } } if (!dw) { - for (int i = 0; !dw && i < info->item_list.count(); ++i) { + for (int i = 0; !dw && i < info->item_list.size(); ++i) { const QDockAreaLayoutItem &item = info->item_list.at(i); if (item.skip()) continue; @@ -1470,7 +1470,7 @@ inline static Qt::DockWidgetArea toDockWidgetArea(int pos) #if QT_CONFIG(dockwidget) static bool isAreaAllowed(QWidget *widget, const QList<int> &path) { - Q_ASSERT_X((path.count() > 1), "isAreaAllowed", "invalid path size"); + Q_ASSERT_X((path.size() > 1), "isAreaAllowed", "invalid path size"); const Qt::DockWidgetArea area = toDockWidgetArea(path[1]); // Read permissions directly from a single dock widget @@ -1485,7 +1485,7 @@ static bool isAreaAllowed(QWidget *widget, const QList<int> &path) if (QDockWidgetGroupWindow *dwgw = qobject_cast<QDockWidgetGroupWindow *>(widget)) { const QList<QDockWidget *> children = dwgw->findChildren<QDockWidget *>(QString(), Qt::FindDirectChildrenOnly); - if (children.count() == 1) { + if (children.size() == 1) { // Group window has a single child => read its permissions const bool allowed = children.at(0)->isAreaAllowed(area); if (!allowed) @@ -1493,7 +1493,7 @@ static bool isAreaAllowed(QWidget *widget, const QList<int> &path) return allowed; } else { // Group window has more than one or no children => dock it anywhere - qCDebug(lcQpaDockWidgets) << "DockWidgetGroupWindow" << widget << "has" << children.count() << "children:"; + qCDebug(lcQpaDockWidgets) << "DockWidgetGroupWindow" << widget << "has" << children.size() << "children:"; qCDebug(lcQpaDockWidgets) << children; qCDebug(lcQpaDockWidgets) << "DockWidgetGroupWindow" << widget << "can dock at" << area << "and anywhere else."; return true; @@ -1588,9 +1588,9 @@ void QMainWindowLayout::setDocumentMode(bool enabled) _documentMode = enabled; // Update the document mode for all tab bars - for (QTabBar *bar : qAsConst(usedTabBars)) + for (QTabBar *bar : std::as_const(usedTabBars)) bar->setDocumentMode(_documentMode); - for (QTabBar *bar : qAsConst(unusedTabBars)) + for (QTabBar *bar : std::as_const(unusedTabBars)) bar->setDocumentMode(_documentMode); } @@ -2654,6 +2654,36 @@ QLayoutItem *QMainWindowLayout::unplug(QWidget *widget, bool group) } else #endif // QT_CONFIG(tabwidget) { + // Dock widget is unplugged from a main window dock + // => height or width need to be decreased by separator size + switch (dockWidgetArea(dw)) { + case Qt::LeftDockWidgetArea: + case Qt::RightDockWidgetArea: + r.setHeight(r.height() - sep); + break; + case Qt::TopDockWidgetArea: + case Qt::BottomDockWidgetArea: + r.setWidth(r.width() - sep); + break; + case Qt::NoDockWidgetArea: + case Qt::DockWidgetArea_Mask: + break; + } + + // Depending on the title bar layout (vertical / horizontal), + // width and height have to provide minimum space for window handles + // and mouse dragging. + // Assuming horizontal title bar, if the dock widget does not have a layout. + const auto *layout = qobject_cast<QDockWidgetLayout *>(dw->layout()); + const bool verticalTitleBar = layout ? layout->verticalTitleBar : false; + const int tbHeight = QApplication::style() + ? QApplication::style()->pixelMetric(QStyle::PixelMetric::PM_TitleBarHeight) + : 20; + const int minHeight = verticalTitleBar ? 2 * tbHeight : tbHeight; + const int minWidth = verticalTitleBar ? tbHeight : 2 * tbHeight; + r.setSize(r.size().expandedTo(QSize(minWidth, minHeight))); + qCDebug(lcQpaDockWidgets) << dw << "will be unplugged with size" << r.size(); + dw->d_func()->unplug(r); } } @@ -2977,7 +3007,7 @@ bool QMainWindowLayout::restoreState(QDataStream &stream) #if QT_CONFIG(dockwidget) if (parentWidget()->isVisible()) { #if QT_CONFIG(tabbar) - for (QTabBar *tab_bar : qAsConst(usedTabBars)) + for (QTabBar *tab_bar : std::as_const(usedTabBars)) tab_bar->show(); #endif diff --git a/src/widgets/widgets/qmdiarea.cpp b/src/widgets/widgets/qmdiarea.cpp index afa89b243b..8708e343fd 100644 --- a/src/widgets/widgets/qmdiarea.cpp +++ b/src/widgets/widgets/qmdiarea.cpp @@ -434,8 +434,8 @@ QList<QRect> MinOverlapPlacer::getCandidatePlacements(const QSize &size, const Q ylist.erase(std::unique(ylist.begin(), ylist.end()), ylist.end()); result.reserve(ylist.size() * xlist.size()); - for (int y : qAsConst(ylist)) - for (int x : qAsConst(xlist)) + for (int y : std::as_const(ylist)) + for (int x : std::as_const(xlist)) result << QRect(QPoint(x, y), size); return result; } @@ -750,7 +750,7 @@ void QMdiAreaPrivate::_q_currentTabChanged(int index) // If the previous active sub-window was hidden, disable the tab. if (indexToLastActiveTab >= 0 && indexToLastActiveTab < tabBar->count() - && indexToLastActiveTab < childWindows.count()) { + && indexToLastActiveTab < childWindows.size()) { QMdiSubWindow *lastActive = childWindows.at(indexToLastActiveTab); if (lastActive && lastActive->isHidden()) tabBar->setTabEnabled(indexToLastActiveTab, false); @@ -824,7 +824,7 @@ void QMdiAreaPrivate::appendChild(QMdiSubWindow *child) if (tabBar) { tabBar->addTab(child->windowIcon(), tabTextFor(child)); updateTabBarGeometry(); - if (childWindows.count() == 1 && !(options & QMdiArea::DontMaximizeSubWindowOnActivation)) + if (childWindows.size() == 1 && !(options & QMdiArea::DontMaximizeSubWindowOnActivation)) showActiveWindowMaximized = true; } #endif @@ -919,7 +919,7 @@ void QMdiAreaPrivate::rearrange(Rearranger *rearranger) QRect domain = viewport->rect(); if (rearranger->type() == Rearranger::RegularTiler && !widgets.isEmpty()) - domain = resizeToMinimumTileSize(minSubWindowSize, widgets.count()); + domain = resizeToMinimumTileSize(minSubWindowSize, widgets.size()); rearranger->rearrange(widgets, domain); @@ -1296,7 +1296,7 @@ bool QMdiAreaPrivate::scrollBarsEnabled() const */ bool QMdiAreaPrivate::lastWindowAboutToBeDestroyed() const { - if (childWindows.count() != 1) + if (childWindows.size() != 1) return false; QMdiSubWindow *last = childWindows.at(0); @@ -1372,7 +1372,7 @@ QMdiAreaPrivate::subWindowList(QMdiArea::WindowOrder order, bool reversed) const } } else { // ActivationHistoryOrder Q_ASSERT(indicesToActivatedChildren.size() == childWindows.size()); - for (int i = indicesToActivatedChildren.count() - 1; i >= 0; --i) { + for (int i = indicesToActivatedChildren.size() - 1; i >= 0; --i) { QMdiSubWindow *child = childWindows.at(indicesToActivatedChildren.at(i)); if (!child) continue; @@ -1761,7 +1761,7 @@ QMdiSubWindow *QMdiArea::currentSubWindow() const if (d->isActivated && !window()->isMinimized()) return nullptr; - Q_ASSERT(d->indicesToActivatedChildren.count() > 0); + Q_ASSERT(d->indicesToActivatedChildren.size() > 0); int index = d->indicesToActivatedChildren.at(0); Q_ASSERT(index >= 0 && index < d->childWindows.size()); QMdiSubWindow *current = d->childWindows.at(index); diff --git a/src/widgets/widgets/qmenu.cpp b/src/widgets/widgets/qmenu.cpp index eaca88dfa7..861af005e5 100644 --- a/src/widgets/widgets/qmenu.cpp +++ b/src/widgets/widgets/qmenu.cpp @@ -110,7 +110,7 @@ public: //QObject::connect(this, SIGNAL(triggered(QAction*)), this, SLOT(onTrigger(QAction*))); //QObject::connect(this, SIGNAL(hovered(QAction*)), this, SLOT(onHovered(QAction*))); QList<QAction*> items = p->actions(); - for(int i = 0; i < items.count(); i++) + for(int i = 0; i < items.size(); i++) addAction(items.at(i)); d->setMenuSize(sizeHint()); d->initialized = true; @@ -335,7 +335,7 @@ void QMenuPrivate::updateActionRects(const QRect &screen) const q->ensurePolished(); //let's reinitialize the buffer - actionRects.resize(actions.count()); + actionRects.resize(actions.size()); actionRects.fill(QRect()); int lastVisibleAction = getLastVisibleAction(); @@ -360,7 +360,7 @@ void QMenuPrivate::updateActionRects(const QRect &screen) const hasCheckableItems = false; ncols = 1; - for (int i = 0; i < actions.count(); ++i) { + for (int i = 0; i < actions.size(); ++i) { QAction *action = actions.at(i); if (action->isSeparator() || !action->isVisible() || widgetItems.contains(action)) continue; @@ -454,7 +454,7 @@ void QMenuPrivate::updateActionRects(const QRect &screen) const int x = hmargin + fw + leftmargin; y = base_y; - for(int i = 0; i < actions.count(); i++) { + for(int i = 0; i < actions.size(); i++) { QRect &rect = actionRects[i]; if (rect.isNull()) continue; @@ -479,7 +479,7 @@ void QMenuPrivate::updateActionRects(const QRect &screen) const int QMenuPrivate::getLastVisibleAction() const { //let's try to get the last visible action - int lastVisibleAction = actions.count() - 1; + int lastVisibleAction = actions.size() - 1; for (;lastVisibleAction >= 0; --lastVisibleAction) { const QAction *action = actions.at(lastVisibleAction); if (action->isVisible()) { @@ -661,7 +661,7 @@ void QMenuPrivate::setFirstActionActive() { Q_Q(QMenu); updateActionRects(); - for(int i = 0, saccum = 0; i < actions.count(); i++) { + for(int i = 0, saccum = 0; i < actions.size(); i++) { const QRect &rect = actionRects.at(i); if (rect.isNull()) continue; @@ -898,7 +898,7 @@ QAction *QMenuPrivate::actionAt(QPoint p) const if (!rect().contains(p)) //sanity check return nullptr; - for(int i = 0; i < actionRects.count(); i++) { + for(int i = 0; i < actionRects.size(); i++) { if (actionRects.at(i).contains(p)) return actions.at(i); } @@ -1109,7 +1109,7 @@ void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation loc const int fw = q->style()->pixelMetric(QStyle::PM_MenuPanelWidth, nullptr, q); if (location == QMenuScroller::ScrollTop) { - for(int i = 0, saccum = 0; i < actions.count(); i++) { + for(int i = 0, saccum = 0; i < actions.size(); i++) { if (actions.at(i) == action) { newOffset = topScroll - saccum; break; @@ -1117,7 +1117,7 @@ void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation loc saccum += actionRects.at(i).height(); } } else { - for(int i = 0, saccum = 0; i < actions.count(); i++) { + for(int i = 0, saccum = 0; i < actions.size(); i++) { saccum += actionRects.at(i).height(); if (actions.at(i) == action) { if (location == QMenuScroller::ScrollCenter) @@ -1136,7 +1136,7 @@ void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation loc if (newOffset < 0) //easy and cheap one newScrollFlags |= QMenuScroller::ScrollUp; int saccum = newOffset; - for(int i = 0; i < actionRects.count(); i++) { + for(int i = 0; i < actionRects.size(); i++) { saccum += actionRects.at(i).height(); if (saccum > q->height()) { newScrollFlags |= QMenuScroller::ScrollDown; @@ -1193,7 +1193,7 @@ void QMenuPrivate::scrollMenu(QAction *action, QMenuScroller::ScrollLocation loc const int delta = qMin(0, newOffset) - scroll->scrollOffset; //make sure the new offset is always negative if (!itemsDirty && delta) { //we've scrolled so we need to update the action rects - for (int i = 0; i < actionRects.count(); ++i) { + for (int i = 0; i < actionRects.size(); ++i) { QRect ¤t = actionRects[i]; current.moveTop(current.top() + delta); @@ -1260,7 +1260,7 @@ void QMenuPrivate::scrollMenu(QMenuScroller::ScrollDirection direction, bool pag const int fw = q->style()->pixelMetric(QStyle::PM_MenuPanelWidth, nullptr, q); const int offset = topScroll ? topScroll-vmargin : 0; if (direction == QMenuScroller::ScrollUp) { - for(int i = 0, saccum = 0; i < actions.count(); i++) { + for(int i = 0, saccum = 0; i < actions.size(); i++) { saccum -= actionRects.at(i).height(); if (saccum <= scroll->scrollOffset-offset) { scrollMenu(actions.at(i), page ? QMenuScroller::ScrollBottom : QMenuScroller::ScrollTop, active); @@ -1269,13 +1269,13 @@ void QMenuPrivate::scrollMenu(QMenuScroller::ScrollDirection direction, bool pag } } else if (direction == QMenuScroller::ScrollDown) { bool scrolled = false; - for(int i = 0, saccum = 0; i < actions.count(); i++) { + for(int i = 0, saccum = 0; i < actions.size(); i++) { const int iHeight = actionRects.at(i).height(); saccum -= iHeight; if (saccum <= scroll->scrollOffset-offset) { const int scrollerArea = q->height() - botScroll - fw*2; int visible = (scroll->scrollOffset-offset) - saccum; - for(i++ ; i < actions.count(); i++) { + for(i++ ; i < actions.size(); i++) { visible += actionRects.at(i).height(); if (visible > scrollerArea - topScroll) { scrolled = true; @@ -1387,9 +1387,18 @@ bool QMenuPrivate::mouseEventTaken(QMouseEvent *e) void QMenuPrivate::activateCausedStack(const QList<QPointer<QWidget>> &causedStack, QAction *action, QAction::ActionEvent action_e, bool self) { - QBoolBlocker guard(activationRecursionGuard); + Q_Q(QMenu); + // can't use QBoolBlocker here + const bool activationRecursionGuardReset = activationRecursionGuard; + activationRecursionGuard = true; + QPointer<QMenu> guard(q); if (self) action->activate(action_e); + if (!guard) + return; + auto boolBlocker = qScopeGuard([this, activationRecursionGuardReset]{ + activationRecursionGuard = activationRecursionGuardReset; + }); for(int i = 0; i < causedStack.size(); ++i) { QPointer<QWidget> widget = causedStack.at(i); @@ -1465,9 +1474,10 @@ void QMenuPrivate::activateAction(QAction *action, QAction::ActionEvent action_e #endif } - + QPointer<QMenu> thisGuard(q); activateCausedStack(causedStack, action, action_e, self); - + if (!thisGuard) + return; if (action_e == QAction::Hover) { #if QT_CONFIG(accessibility) @@ -2173,7 +2183,7 @@ QAction *QMenu::activeAction() const bool QMenu::isEmpty() const { bool ret = true; - for(int i = 0; ret && i < actions().count(); ++i) { + for(int i = 0; ret && i < actions().size(); ++i) { const QAction *action = actions().at(i); if (!action->isSeparator() && action->isVisible()) { ret = false; @@ -2238,7 +2248,7 @@ QSize QMenu::sizeHint() const d->updateActionRects(); QSize s; - for (int i = 0; i < d->actionRects.count(); ++i) { + for (int i = 0; i < d->actionRects.size(); ++i) { const QRect &rect = d->actionRects.at(i); if (rect.isNull()) continue; @@ -2383,7 +2393,7 @@ void QMenuPrivate::popup(const QPoint &p, QAction *atAction, PositionFunction po atAction = defaultAction; // TODO: This works for first level menus, not yet sub menus } else { - for (QAction *action : qAsConst(actions)) + for (QAction *action : std::as_const(actions)) if (action->isEnabled()) { atAction = action; break; @@ -2395,7 +2405,7 @@ void QMenuPrivate::popup(const QPoint &p, QAction *atAction, PositionFunction po if (ncols > 1) { pos.setY(screen.top() + desktopFrame); } else if (atAction) { - for (int i = 0, above_height = 0; i < actions.count(); i++) { + for (int i = 0, above_height = 0; i < actions.size(); i++) { QAction *action = actions.at(i); if (action == atAction) { int newY = pos.y() - above_height; @@ -2410,7 +2420,7 @@ void QMenuPrivate::popup(const QPoint &p, QAction *atAction, PositionFunction po if (scroll && scroll->scrollFlags != QMenuPrivate::QMenuScroller::ScrollNone && !q->style()->styleHint(QStyle::SH_Menu_FillScreenWithScroll, nullptr, q)) { int below_height = above_height + scroll->scrollOffset; - for (int i2 = i; i2 < actionRects.count(); i2++) + for (int i2 = i; i2 < actionRects.size(); i2++) below_height += actionRects.at(i2).height(); size.setHeight(below_height); } @@ -2744,7 +2754,7 @@ void QMenu::paintEvent(QPaintEvent *e) //draw the items that need updating.. QRect scrollUpTearOffRect = scrollUpRect.united(tearOffRect); - for (int i = 0; i < d->actions.count(); ++i) { + for (int i = 0; i < d->actions.size(); ++i) { QAction *action = d->actions.at(i); QRect actionRect = d->actionRects.at(i); if (!e->rect().intersects(actionRect) @@ -3088,7 +3098,7 @@ void QMenu::keyPressEvent(QKeyEvent *e) QMenuPrivate::QMenuScroller::ScrollLocation scroll_loc = QMenuPrivate::QMenuScroller::ScrollStay; if (!d->currentAction) { if (key == Qt::Key_Down) { - for(int i = 0; i < d->actions.count(); ++i) { + for(int i = 0; i < d->actions.size(); ++i) { QAction *act = d->actions.at(i); if (d->actionRects.at(i).isNull()) continue; @@ -3100,7 +3110,7 @@ void QMenu::keyPressEvent(QKeyEvent *e) } } } else { - for(int i = d->actions.count()-1; i >= 0; --i) { + for(int i = d->actions.size()-1; i >= 0; --i) { QAction *act = d->actions.at(i); if (d->actionRects.at(i).isNull()) continue; @@ -3113,7 +3123,7 @@ void QMenu::keyPressEvent(QKeyEvent *e) } } } else { - for(int i = 0, y = 0; !nextAction && i < d->actions.count(); i++) { + for(int i = 0, y = 0; !nextAction && i < d->actions.size(); i++) { QAction *act = d->actions.at(i); if (act == d->currentAction) { if (key == Qt::Key_Up) { @@ -3123,7 +3133,7 @@ void QMenu::keyPressEvent(QKeyEvent *e) break; if (d->scroll) scroll_loc = QMenuPrivate::QMenuScroller::ScrollBottom; - next_i = d->actionRects.count()-1; + next_i = d->actionRects.size()-1; } QAction *next = d->actions.at(next_i); if (next == d->currentAction) @@ -3149,7 +3159,7 @@ void QMenu::keyPressEvent(QKeyEvent *e) } else { y += d->actionRects.at(i).height(); for(int next_i = i+1; true; next_i++) { - if (next_i == d->actionRects.count()) { + if (next_i == d->actionRects.size()) { if (!style()->styleHint(QStyle::SH_Menu_SelectionWrap, nullptr, this)) break; if (d->scroll) @@ -3306,7 +3316,7 @@ void QMenu::keyPressEvent(QKeyEvent *e) if (!key_consumed) { // send to menu bar if ((!e->modifiers() || e->modifiers() == Qt::AltModifier || e->modifiers() == Qt::ShiftModifier) && - e->text().length()==1) { + e->text().size()==1) { bool activateAction = false; QAction *nextAction = nullptr; if (style()->styleHint(QStyle::SH_Menu_KeyboardSearch, nullptr, this) && !e->modifiers()) { diff --git a/src/widgets/widgets/qmenubar.cpp b/src/widgets/widgets/qmenubar.cpp index 15c6f521b3..bc690029e9 100644 --- a/src/widgets/widgets/qmenubar.cpp +++ b/src/widgets/widgets/qmenubar.cpp @@ -168,7 +168,7 @@ void QMenuBarPrivate::updateGeometries() for(int j = 0; j < shortcutIndexMap.size(); ++j) q->releaseShortcut(shortcutIndexMap.value(j)); shortcutIndexMap.clear(); - const int actionsCount = actions.count(); + const int actionsCount = actions.size(); shortcutIndexMap.reserve(actionsCount); for (int i = 0; i < actionsCount; i++) shortcutIndexMap.append(q->grabShortcut(QKeySequence::mnemonic(actions.at(i)->text()))); @@ -182,7 +182,7 @@ void QMenuBarPrivate::updateGeometries() //we try to see if the actions will fit there bool hasHiddenActions = false; - for (int i = 0; i < actions.count(); ++i) { + for (int i = 0; i < actions.size(); ++i) { const QRect &rect = actionRects.at(i); if (rect.isValid() && !menuRect.contains(rect)) { hasHiddenActions = true; @@ -193,7 +193,7 @@ void QMenuBarPrivate::updateGeometries() //...and if not, determine the ones that fit on the menu with the extension visible if (hasHiddenActions) { menuRect = this->menuRect(true); - for (int i = 0; i < actions.count(); ++i) { + for (int i = 0; i < actions.size(); ++i) { const QRect &rect = actionRects.at(i); if (rect.isValid() && !menuRect.contains(rect)) { hiddenActions.append(actions.at(i)); @@ -201,7 +201,7 @@ void QMenuBarPrivate::updateGeometries() } } - if (hiddenActions.count() > 0) { + if (hiddenActions.size() > 0) { QMenu *pop = extension->menu(); if (!pop) { pop = new QMenu(q); @@ -229,7 +229,7 @@ QRect QMenuBarPrivate::actionRect(QAction *act) const //makes sure the geometries are up-to-date const_cast<QMenuBarPrivate*>(this)->updateGeometries(); - if (index < 0 || index >= actionRects.count()) + if (index < 0 || index >= actionRects.size()) return QRect(); // that can happen in case of native menubar return actionRects.at(index); @@ -240,8 +240,8 @@ void QMenuBarPrivate::focusFirstAction() if (!currentAction) { updateGeometries(); int index = 0; - while (index < actions.count() && actionRects.at(index).isNull()) ++index; - if (index < actions.count()) + while (index < actions.size() && actionRects.at(index).isNull()) ++index; + if (index < actions.size()) setCurrentAction(actions.at(index)); } } @@ -378,7 +378,7 @@ void QMenuBarPrivate::calcActionRects(int max_width, int start) const return; //let's reinitialize the buffer - actionRects.resize(actions.count()); + actionRects.resize(actions.size()); actionRects.fill(QRect()); const QStyle *style = q->style(); @@ -391,7 +391,7 @@ void QMenuBarPrivate::calcActionRects(int max_width, int start) const const int hmargin = style->pixelMetric(QStyle::PM_MenuBarHMargin, nullptr, q), vmargin = style->pixelMetric(QStyle::PM_MenuBarVMargin, nullptr, q), icone = style->pixelMetric(QStyle::PM_SmallIconSize, nullptr, q); - for(int i = 0; i < actions.count(); i++) { + for(int i = 0; i < actions.size(); i++) { QAction *action = actions.at(i); if (!action->isVisible()) continue; @@ -437,7 +437,7 @@ void QMenuBarPrivate::calcActionRects(int max_width, int start) const const int fw = q->style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, nullptr, q); int x = fw + ((start == -1) ? hmargin : start) + itemSpacing; int y = fw + vmargin; - for(int i = 0; i < actions.count(); i++) { + for(int i = 0; i < actions.size(); i++) { QRect &rect = actionRects[i]; if (rect.isNull()) continue; @@ -680,8 +680,8 @@ QAction *QMenuBarPrivate::getNextAction(const int _start, const int increment) c Q_Q(const QMenuBar); const_cast<QMenuBarPrivate*>(this)->updateGeometries(); bool allowActiveAndDisabled = q->style()->styleHint(QStyle::SH_Menu_AllowActiveAndDisabled, nullptr, q); - const int start = (_start == -1 && increment == -1) ? actions.count() : _start; - const int end = increment == -1 ? 0 : actions.count() - 1; + const int start = (_start == -1 && increment == -1) ? actions.size() : _start; + const int end = increment == -1 ? 0 : actions.size() - 1; for (int i = start; i != end;) { i += increment; @@ -884,7 +884,7 @@ void QMenuBar::paintEvent(QPaintEvent *e) QRegion emptyArea(rect()); //draw the items - for (int i = 0; i < d->actions.count(); ++i) { + for (int i = 0; i < d->actions.size(); ++i) { QAction *action = d->actions.at(i); QRect adjustedActionRect = d->actionRect(action); if (adjustedActionRect.isEmpty() || !d->isVisible(action)) @@ -1060,7 +1060,7 @@ void QMenuBar::keyPressEvent(QKeyEvent *e) if (!key_consumed && (!e->modifiers() || - (e->modifiers()&(Qt::MetaModifier|Qt::AltModifier))) && e->text().length()==1 && !d->popupState) { + (e->modifiers()&(Qt::MetaModifier|Qt::AltModifier))) && e->text().size()==1 && !d->popupState) { int clashCount = 0; QAction *first = nullptr, *currentSelected = nullptr, *firstAfterCurrent = nullptr; { @@ -1525,7 +1525,7 @@ QSize QMenuBar::minimumSizeHint() const if (as_gui_menubar) { int w = parentWidget() ? parentWidget()->width() : QGuiApplication::primaryScreen()->virtualGeometry().width(); d->calcActionRects(w - (2 * fw), 0); - for (int i = 0; ret.isNull() && i < d->actions.count(); ++i) + for (int i = 0; ret.isNull() && i < d->actions.size(); ++i) ret = d->actionRects.at(i).size(); if (!d->extension->isHidden()) ret += QSize(d->extension->sizeHint().width(), 0); @@ -1575,7 +1575,7 @@ QSize QMenuBar::sizeHint() const if (as_gui_menubar) { const int w = parentWidget() ? parentWidget()->width() : QGuiApplication::primaryScreen()->virtualGeometry().width(); d->calcActionRects(w - (2 * fw), 0); - for (int i = 0; i < d->actionRects.count(); ++i) { + for (int i = 0; i < d->actionRects.size(); ++i) { const QRect &actionRect = d->actionRects.at(i); ret = ret.expandedTo(QSize(actionRect.x() + actionRect.width(), actionRect.y() + actionRect.height())); } @@ -1622,7 +1622,7 @@ int QMenuBar::heightForWidth(int) const int fw = style()->pixelMetric(QStyle::PM_MenuBarPanelWidth, nullptr, this); int spaceBelowMenuBar = style()->styleHint(QStyle::SH_MainWindow_SpaceBelowMenuBar, nullptr, this); if (as_gui_menubar) { - for (int i = 0; i < d->actionRects.count(); ++i) + for (int i = 0; i < d->actionRects.size(); ++i) height = qMax(height, d->actionRects.at(i).height()); if (height) //there is at least one non-null item height += spaceBelowMenuBar; @@ -1772,6 +1772,7 @@ void QMenuBar::setNativeMenuBar(bool nativeMenuBar) if (!nativeMenuBar) { delete d->platformMenuBar; d->platformMenuBar = nullptr; + d->itemsDirty = true; } else { if (!d->platformMenuBar) d->platformMenuBar = QGuiApplicationPrivate::platformTheme()->createPlatformMenuBar(); diff --git a/src/widgets/widgets/qplaintextedit.cpp b/src/widgets/widgets/qplaintextedit.cpp index cd9889e9ff..f41e7f009b 100644 --- a/src/widgets/widgets/qplaintextedit.cpp +++ b/src/widgets/widgets/qplaintextedit.cpp @@ -622,10 +622,7 @@ void QPlainTextEditPrivate::setTopBlock(int blockNumber, int lineNumber, int dx) lineNumber = maxTopLine - block.firstLineNumber(); } - { - const QSignalBlocker blocker(vbar); - vbar->setValue(newTopLine); - } + vbar->setValue(newTopLine); if (!dx && blockNumber == control->topBlock && lineNumber == topLine) return; @@ -641,10 +638,7 @@ void QPlainTextEditPrivate::setTopBlock(int blockNumber, int lineNumber, int dx) control->topBlock = blockNumber; topLine = lineNumber; - { - const QSignalBlocker blocker(vbar); - vbar->setValue(block.firstLineNumber() + lineNumber); - } + vbar->setValue(block.firstLineNumber() + lineNumber); if (dx || dy) { viewport->scroll(q->isRightToLeft() ? -dx : dx, dy); @@ -1002,10 +996,7 @@ void QPlainTextEditPrivate::_q_adjustScrollbars() if (firstVisibleBlock.isValid()) visualTopLine = firstVisibleBlock.firstLineNumber() + topLine; - { - const QSignalBlocker blocker(vbar); - vbar->setValue(visualTopLine); - } + vbar->setValue(visualTopLine); hbar->setRange(0, (int)documentSize.width() - viewport->width()); hbar->setPageStep(viewport->width()); diff --git a/src/widgets/widgets/qscrollbar.cpp b/src/widgets/widgets/qscrollbar.cpp index ed456c56b8..28794bfdcc 100644 --- a/src/widgets/widgets/qscrollbar.cpp +++ b/src/widgets/widgets/qscrollbar.cpp @@ -189,7 +189,9 @@ void QScrollBarPrivate::setTransient(bool value) if (transient != value) { transient = value; if (q->isVisible()) { - if (q->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, q)) + QStyleOptionSlider opt; + q->initStyleOption(&opt); + if (q->style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, q)) q->update(); } else if (!transient) { q->show(); @@ -200,7 +202,9 @@ void QScrollBarPrivate::setTransient(bool value) void QScrollBarPrivate::flash() { Q_Q(QScrollBar); - if (!flashed && q->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, q)) { + QStyleOptionSlider opt; + q->initStyleOption(&opt); + if (!flashed && q->style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, q)) { flashed = true; if (!q->isVisible()) q->show(); @@ -284,7 +288,7 @@ void QScrollBar::initStyleOption(QStyleOptionSlider *option) const option->upsideDown = d->invertedAppearance; if (d->orientation == Qt::Horizontal) option->state |= QStyle::State_Horizontal; - if ((d->flashed || !d->transient) && style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, this)) + if ((d->flashed || !d->transient) && style()->styleHint(QStyle::SH_ScrollBar_Transient, option, this)) option->state |= QStyle::State_On; } @@ -341,7 +345,9 @@ void QScrollBarPrivate::init() invertedControls = true; pressedControl = hoverControl = QStyle::SC_None; pointerOutsidePressedControl = false; - transient = q->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, q); + QStyleOption opt; + opt.initFrom(q); + transient = q->style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, q); flashed = false; flashTimer = 0; q->setFocusPolicy(Qt::NoFocus); @@ -435,12 +441,17 @@ bool QScrollBar::event(QEvent *event) if (const QHoverEvent *he = static_cast<const QHoverEvent *>(event)) d_func()->updateHoverControl(he->position().toPoint()); break; - case QEvent::StyleChange: - d_func()->setTransient(style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, this)); + case QEvent::StyleChange: { + QStyleOptionSlider opt; + initStyleOption(&opt); + d_func()->setTransient(style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, this)); break; + } case QEvent::Timer: if (static_cast<QTimerEvent *>(event)->timerId() == d->flashTimer) { - if (d->flashed && style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, this)) { + QStyleOptionSlider opt; + initStyleOption(&opt); + if (d->flashed && style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, this)) { d->flashed = false; update(); } diff --git a/src/widgets/widgets/qsplitter.cpp b/src/widgets/widgets/qsplitter.cpp index a954d6ce66..84c3799494 100644 --- a/src/widgets/widgets/qsplitter.cpp +++ b/src/widgets/widgets/qsplitter.cpp @@ -361,7 +361,7 @@ void QSplitterPrivate::init() void QSplitterPrivate::recalc(bool update) { Q_Q(QSplitter); - int n = list.count(); + int n = list.size(); /* Splitter handles before the first visible widget or right before a hidden widget must be hidden. @@ -451,7 +451,7 @@ void QSplitterPrivate::doResize() { Q_Q(QSplitter); QRect r = q->contentsRect(); - int n = list.count(); + int n = list.size(); QList<QLayoutStruct> a(n * 2); int i; @@ -565,7 +565,7 @@ int QSplitterPrivate::findWidgetJustBeforeOrJustAfter(int index, int delta, int return index; } index += delta; - } while (index >= 0 && index < list.count()); + } while (index >= 0 && index < list.size()); return -1; } @@ -577,7 +577,7 @@ int QSplitterPrivate::findWidgetJustBeforeOrJustAfter(int index, int delta, int void QSplitterPrivate::getRange(int index, int *farMin, int *min, int *max, int *farMax) const { Q_Q(const QSplitter); - int n = list.count(); + int n = list.size(); if (index <= 0 || index >= n) return; @@ -757,7 +757,7 @@ void QSplitterPrivate::setGeo(QSplitterLayoutStruct *sls, int p, int s, bool all void QSplitterPrivate::doMove(bool backwards, int hPos, int index, int delta, bool mayCollapse, int *positions, int *widths) { - if (index < 0 || index >= list.count()) + if (index < 0 || index >= list.size()) return; #ifdef QSPLITTER_DEBUG @@ -827,7 +827,7 @@ QSplitterLayoutStruct *QSplitterPrivate::insertWidget(int index, QWidget *w) Q_Q(QSplitter); QSplitterLayoutStruct *sls = nullptr; int i; - int last = list.count(); + int last = list.size(); for (i = 0; i < list.size(); ++i) { QSplitterLayoutStruct *s = list.at(i); if (s->widget == w) { @@ -1079,7 +1079,7 @@ void QSplitter::resizeEvent(QResizeEvent *) void QSplitter::addWidget(QWidget *widget) { Q_D(QSplitter); - insertWidget(d->list.count(), widget); + insertWidget(d->list.size(), widget); } /*! @@ -1129,7 +1129,7 @@ QWidget *QSplitter::replaceWidget(int index, QWidget *widget) return nullptr; } - if (index < 0 || index >= d->list.count()) { + if (index < 0 || index >= d->list.size()) { qWarning("QSplitter::replaceWidget: Index %d out of range", index); return nullptr; } @@ -1242,7 +1242,7 @@ QWidget *QSplitter::widget(int index) const int QSplitter::count() const { Q_D(const QSplitter); - return d->list.count(); + return d->list.size(); } /*! @@ -1271,7 +1271,7 @@ void QSplitter::childEvent(QChildEvent *c) } QWidget *w = static_cast<QWidget*>(c->child()); if (!d->blockChildAdd && !w->isWindow() && !d->findWidget(w)) - d->insertWidget_helper(d->list.count(), w, false); + d->insertWidget_helper(d->list.size(), w, false); } else if (c->polished()) { if (!c->child()->isWidgetType()) return; @@ -1398,15 +1398,15 @@ void QSplitter::moveSplitter(int pos, int index) qDebug() << "QSplitter::moveSplitter" << debugp << index << "adjusted" << pos << "oldP" << oldP; #endif - QVarLengthArray<int, 32> poss(d->list.count()); - QVarLengthArray<int, 32> ws(d->list.count()); + QVarLengthArray<int, 32> poss(d->list.size()); + QVarLengthArray<int, 32> ws(d->list.size()); bool upLeft; d->doMove(false, pos, index, +1, (d->collapsible(s) && (pos > max)), poss.data(), ws.data()); d->doMove(true, pos, index - 1, +1, (d->collapsible(index - 1) && (pos < min)), poss.data(), ws.data()); upLeft = (pos < oldP); - int wid, delta, count = d->list.count(); + int wid, delta, count = d->list.size(); if (upLeft) { wid = 0; delta = 1; @@ -1751,7 +1751,7 @@ bool QSplitter::restoreState(const QByteArray &state) void QSplitter::setStretchFactor(int index, int stretch) { Q_D(QSplitter); - if (index <= -1 || index >= d->list.count()) + if (index <= -1 || index >= d->list.size()) return; QWidget *widget = d->list.at(index)->widget; diff --git a/src/widgets/widgets/qstatusbar.cpp b/src/widgets/widgets/qstatusbar.cpp index d5ae7d5cd2..2cd3ac3036 100644 --- a/src/widgets/widgets/qstatusbar.cpp +++ b/src/widgets/widgets/qstatusbar.cpp @@ -355,19 +355,10 @@ void QStatusBar::removeWidget(QWidget *widget) return; Q_D(QStatusBar); - bool found = false; - for (int i = 0; i < d->items.size(); ++i) { - const auto &item = d->items.at(i); - if (item.widget == widget) { - d->items.removeAt(i); - item.widget->hide(); - found = true; - break; - } - } - - if (found) + if (d->items.removeIf([widget](const auto &item) { return item.widget == widget; })) { + widget->hide(); reformat(); + } #if defined(QT_DEBUG) else qDebug("QStatusBar::removeWidget(): Widget not found."); @@ -570,7 +561,7 @@ void QStatusBar::hideOrShow() Q_D(QStatusBar); bool haveMessage = !d->tempItem.isEmpty(); - for (const auto &item : qAsConst(d->items)) { + for (const auto &item : std::as_const(d->items)) { if (item.isPermanent()) break; if (haveMessage && item.widget->isVisible()) { @@ -622,7 +613,7 @@ void QStatusBar::paintEvent(QPaintEvent *event) opt.initFrom(this); style()->drawPrimitive(QStyle::PE_PanelStatusBar, &opt, &p, this); - for (const auto &item : qAsConst(d->items)) { + for (const auto &item : std::as_const(d->items)) { if (item.widget->isVisible() && (!haveMessage || item.isPermanent())) { QRect ir = item.widget->geometry().adjusted(-2, -1, 2, 1); if (event->rect().intersects(ir)) { @@ -661,7 +652,7 @@ bool QStatusBar::event(QEvent *e) // Calculate new strut height and call reformat() if it has changed int maxH = fontMetrics().height(); - for (const auto &item : qAsConst(d->items)) { + for (const auto &item : std::as_const(d->items)) { const int itemH = qMin(qSmartMinSize(item.widget).height(), item.widget->maximumHeight()); maxH = qMax(maxH, itemH); } diff --git a/src/widgets/widgets/qtabbar.cpp b/src/widgets/widgets/qtabbar.cpp index 29b568f29d..155dd80337 100644 --- a/src/widgets/widgets/qtabbar.cpp +++ b/src/widgets/widgets/qtabbar.cpp @@ -404,7 +404,7 @@ int QTabBarPrivate::indexAtPos(const QPoint &p) const Q_Q(const QTabBar); if (q->tabRect(currentIndex).contains(p)) return currentIndex; - for (int i = 0; i < tabList.count(); ++i) + for (int i = 0; i < tabList.size(); ++i) if (tabList.at(i)->enabled && q->tabRect(i).contains(p)) return i; return -1; @@ -422,7 +422,7 @@ void QTabBarPrivate::layoutTabs() int hiddenTabs = 0; Qt::Alignment tabAlignment = Qt::Alignment(q->style()->styleHint(QStyle::SH_TabBar_Alignment, nullptr, q)); - QList<QLayoutStruct> tabChain(tabList.count() + 2); + QList<QLayoutStruct> tabChain(tabList.size() + 2); // We put an empty item at the front and back and set its expansive attribute // depending on tabAlignment and expanding. @@ -445,7 +445,7 @@ void QTabBarPrivate::layoutTabs() int minx = 0; int x = 0; int maxHeight = 0; - for (int i = 0; i < tabList.count(); ++i) { + for (int i = 0; i < tabList.size(); ++i) { const auto tab = tabList.at(i); if (!tab->visible) { ++hiddenTabs; @@ -476,7 +476,7 @@ void QTabBarPrivate::layoutTabs() int miny = 0; int y = 0; int maxWidth = 0; - for (int i = 0; i < tabList.count(); ++i) { + for (int i = 0; i < tabList.size(); ++i) { auto tab = tabList.at(i); if (!tab->visible) { ++hiddenTabs; @@ -511,14 +511,14 @@ void QTabBarPrivate::layoutTabs() && (tabAlignment != Qt::AlignRight) && (tabAlignment != Qt::AlignJustify); tabChain[tabChainIndex].empty = true; - Q_ASSERT(tabChainIndex == tabChain.count() - 1 - hiddenTabs); // add an assert just to make sure. + Q_ASSERT(tabChainIndex == tabChain.size() - 1 - hiddenTabs); // add an assert just to make sure. // Do the calculation - qGeomCalc(tabChain, 0, tabChain.count(), 0, qMax(available, last), 0); + qGeomCalc(tabChain, 0, tabChain.size(), 0, qMax(available, last), 0); // Use the results hiddenTabs = 0; - for (int i = 0; i < tabList.count(); ++i) { + for (int i = 0; i < tabList.size(); ++i) { auto tab = tabList.at(i); if (!tab->visible) { tab->rect = QRect(); @@ -532,7 +532,7 @@ void QTabBarPrivate::layoutTabs() tab->rect.setRect(0, lstruct.pos, maxExtent, lstruct.size); } - if (useScrollButtons && tabList.count() && last > available) { + if (useScrollButtons && tabList.size() && last > available) { const QRect scrollRect = normalizedScrollRect(0); scrollOffset = -scrollRect.left(); @@ -768,7 +768,7 @@ void QTabBarPrivate::_q_closeTab() QObject *object = q->sender(); int tabToClose = -1; QTabBar::ButtonPosition closeSide = (QTabBar::ButtonPosition)q->style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, nullptr, q); - for (int i = 0; i < tabList.count(); ++i) { + for (int i = 0; i < tabList.size(); ++i) { if (closeSide == QTabBar::LeftSide) { if (tabList.at(i)->leftWidget == object) { tabToClose = i; @@ -795,7 +795,7 @@ void QTabBarPrivate::_q_scrollTabs() int i = -1; if (sender == leftB) { - for (i = tabList.count() - 1; i >= 0; --i) { + for (i = tabList.size() - 1; i >= 0; --i) { int start = horizontal ? tabList.at(i)->rect.left() : tabList.at(i)->rect.top(); if (start < scrollRect.left()) { makeVisible(i); @@ -803,7 +803,7 @@ void QTabBarPrivate::_q_scrollTabs() } } } else if (sender == rightB) { - for (i = 0; i < tabList.count(); ++i) { + for (i = 0; i < tabList.size(); ++i) { const auto tabRect = tabList.at(i)->rect; int start = horizontal ? tabRect.left() : tabRect.top(); int end = horizontal ? tabRect.right() : tabRect.bottom(); @@ -950,7 +950,7 @@ int QTabBar::insertTab(int index, const QIcon& icon, const QString &text) { Q_D(QTabBar); if (!d->validIndex(index)) { - index = d->tabList.count(); + index = d->tabList.size(); d->tabList.append(new QTabBarPrivate::Tab(icon, text)); } else { d->tabList.insert(index, new QTabBarPrivate::Tab(icon, text)); @@ -960,7 +960,7 @@ int QTabBar::insertTab(int index, const QIcon& icon, const QString &text) #endif d->firstVisible = qMax(qMin(index, d->firstVisible), 0); d->refresh(); - if (d->tabList.count() == 1) + if (d->tabList.size() == 1) setCurrentIndex(index); else if (index <= d->currentIndex) ++d->currentIndex; @@ -979,7 +979,7 @@ int QTabBar::insertTab(int index, const QIcon& icon, const QString &text) setTabButton(index, closeSide, closeButton); } - for (const auto tab : qAsConst(d->tabList)) { + for (const auto tab : std::as_const(d->tabList)) { if (tab->lastTab >= index) ++tab->lastTab; } @@ -1025,7 +1025,7 @@ void QTabBar::removeTab(int index) int newIndex = removedTab->lastTab; d->tabList.removeAt(index); delete removedTab; - for (auto tab : qAsConst(d->tabList)) { + for (auto tab : std::as_const(d->tabList)) { if (tab->lastTab == index) tab->lastTab = -1; if (tab->lastTab > index) @@ -1469,7 +1469,7 @@ void QTabBar::setIconSize(const QSize &size) int QTabBar::count() const { Q_D(const QTabBar); - return d->tabList.count(); + return d->tabList.size(); } @@ -1512,7 +1512,7 @@ QSize QTabBar::minimumSizeHint() const // Compute the most-elided possible text, for minimumSizeHint static QString computeElidedText(Qt::TextElideMode mode, const QString &text) { - if (text.length() <= 3) + if (text.size() <= 3) return text; static const auto Ellipses = "..."_L1; @@ -1721,7 +1721,7 @@ bool QTabBar::event(QEvent *event) case QEvent::Shortcut: { QShortcutEvent *se = static_cast<QShortcutEvent *>(event); - for (int i = 0; i < d->tabList.count(); ++i) { + for (int i = 0; i < d->tabList.size(); ++i) { const QTabBarPrivate::Tab *tab = d->tabList.at(i); if (tab->shortcutId == se->shortcutId()) { setCurrentIndex(i); @@ -1804,7 +1804,7 @@ void QTabBar::paintEvent(QPaintEvent *) selected = d->pressedIndex; const QRect scrollRect = d->normalizedScrollRect(); - for (int i = 0; i < d->tabList.count(); ++i) + for (int i = 0; i < d->tabList.size(); ++i) optTabBase.tabBarRect |= tabRect(i); optTabBase.selectedTabRect = tabRect(selected); @@ -1826,7 +1826,7 @@ void QTabBar::paintEvent(QPaintEvent *) p.setClipRegion(QRegion(rect()) - buttonRegion); } - for (int i = 0; i < d->tabList.count(); ++i) { + for (int i = 0; i < d->tabList.size(); ++i) { const auto tab = d->tabList.at(i); if (!tab->visible) continue; @@ -1916,7 +1916,7 @@ void QTabBarPrivate::calculateFirstLastVisible(int index, bool visible, bool rem } else { if (remove || (index == firstVisible)) { firstVisible = -1; - for (int i = 0; i < tabList.count(); ++i) { + for (int i = 0; i < tabList.size(); ++i) { if (tabList.at(i)->visible) { firstVisible = i; break; @@ -1925,7 +1925,7 @@ void QTabBarPrivate::calculateFirstLastVisible(int index, bool visible, bool rem } if (remove || (index == lastVisible)) { lastVisible = -1; - for (int i = tabList.count() - 1; i >= 0; --i) { + for (int i = tabList.size() - 1; i >= 0; --i) { if (tabList.at(i)->visible) { lastVisible = i; break; @@ -1943,7 +1943,7 @@ void QTabBarPrivate::calculateFirstLastVisible(int index, bool visible, bool rem int QTabBarPrivate::selectNewCurrentIndexFrom(int fromIndex) { int newindex = -1; - for (int i = fromIndex; i < tabList.count(); ++i) { + for (int i = fromIndex; i < tabList.size(); ++i) { if (at(i)->visible && at(i)->enabled) { newindex = i; break; @@ -2039,7 +2039,7 @@ void QTabBar::moveTab(int from, int to) d->tabList.move(from, to); // update lastTab locations - for (const auto tab : qAsConst(d->tabList)) + for (const auto tab : std::as_const(d->tabList)) tab->lastTab = d->calculateNewPosition(from, to, tab->lastTab); // update external variables @@ -2257,7 +2257,7 @@ void QTabBarPrivate::moveTabFinished(int index) bool cleanup = (pressedIndex == index) || (pressedIndex == -1) || !validIndex(index); bool allAnimationsFinished = true; #if QT_CONFIG(animation) - for (const auto tab : qAsConst(tabList)) { + for (const auto tab : std::as_const(tabList)) { if (tab->animation && tab->animation->state() == QAbstractAnimation::Running) { allAnimationsFinished = false; break; @@ -2267,7 +2267,7 @@ void QTabBarPrivate::moveTabFinished(int index) if (allAnimationsFinished && cleanup) { if (movingTab) movingTab->setVisible(false); // We might not get a mouse release - for (auto tab : qAsConst(tabList)) { + for (auto tab : std::as_const(tabList)) { tab->dragOffset = 0; } if (pressedIndex != -1 && movable) { @@ -2545,7 +2545,7 @@ void QTabBar::setTabsClosable(bool closable) d->closeButtonOnTabs = closable; ButtonPosition closeSide = (ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, nullptr, this); if (!closable) { - for (auto tab : qAsConst(d->tabList)) { + for (auto tab : std::as_const(d->tabList)) { if (closeSide == LeftSide && tab->leftWidget) { tab->leftWidget->deleteLater(); tab->leftWidget = nullptr; @@ -2557,7 +2557,7 @@ void QTabBar::setTabsClosable(bool closable) } } else { bool newButtons = false; - for (int i = 0; i < d->tabList.count(); ++i) { + for (int i = 0; i < d->tabList.size(); ++i) { if (tabButton(i, closeSide)) continue; newButtons = true; @@ -2766,7 +2766,7 @@ void QTabBar::setChangeCurrentOnDrag(bool change) void QTabBar::setTabButton(int index, ButtonPosition position, QWidget *widget) { Q_D(QTabBar); - if (index < 0 || index >= d->tabList.count()) + if (index < 0 || index >= d->tabList.size()) return; if (widget) { widget->setParent(this); diff --git a/src/widgets/widgets/qtabbar_p.h b/src/widgets/widgets/qtabbar_p.h index e38b1ef6f9..a421836b93 100644 --- a/src/widgets/widgets/qtabbar_p.h +++ b/src/widgets/widgets/qtabbar_p.h @@ -184,7 +184,7 @@ public: int indexAtPos(const QPoint &p) const; inline bool isAnimated() const { Q_Q(const QTabBar); return q->style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, q) > 0; } - inline bool validIndex(int index) const { return index >= 0 && index < tabList.count(); } + inline bool validIndex(int index) const { return index >= 0 && index < tabList.size(); } void setCurrentNextEnabledIndex(int offset); void _q_scrollTabs(); diff --git a/src/widgets/widgets/qtextbrowser.cpp b/src/widgets/widgets/qtextbrowser.cpp index 2bab2efc61..1cac46e8a8 100644 --- a/src/widgets/widgets/qtextbrowser.cpp +++ b/src/widgets/widgets/qtextbrowser.cpp @@ -64,13 +64,13 @@ public: HistoryEntry history(int i) const { if (i <= 0) - if (-i < stack.count()) - return stack[stack.count()+i-1]; + if (-i < stack.size()) + return stack[stack.size()+i-1]; else return HistoryEntry(); else - if (i <= forwardStack.count()) - return forwardStack[forwardStack.count()-i]; + if (i <= forwardStack.size()) + return forwardStack[forwardStack.size()-i]; else return HistoryEntry(); } @@ -154,7 +154,7 @@ QString QTextBrowserPrivate::findFile(const QUrl &name) const if (QFileInfo(fileName).isAbsolute()) return fileName; - for (QString path : qAsConst(searchPaths)) { + for (QString path : std::as_const(searchPaths)) { if (!path.endsWith(u'/')) path.append(u'/'); path.append(fileName); @@ -828,11 +828,11 @@ void QTextBrowser::doSetSource(const QUrl &url, QTextDocument::ResourceType type entry.vpos = 0; d->stack.push(entry); - emit backwardAvailable(d->stack.count() > 1); + emit backwardAvailable(d->stack.size() > 1); if (!d->forwardStack.isEmpty() && d->forwardStack.top().url == url) { d->forwardStack.pop(); - emit forwardAvailable(d->forwardStack.count() > 0); + emit forwardAvailable(d->forwardStack.size() > 0); } else { d->forwardStack.clear(); emit forwardAvailable(false); @@ -906,14 +906,14 @@ void QTextBrowser::doSetSource(const QUrl &url, QTextDocument::ResourceType type void QTextBrowser::backward() { Q_D(QTextBrowser); - if (d->stack.count() <= 1) + if (d->stack.size() <= 1) return; // Update the history entry d->forwardStack.push(d->createHistoryEntry()); d->stack.pop(); // throw away the old version of the current entry d->restoreHistoryEntry(d->stack.top()); // previous entry - emit backwardAvailable(d->stack.count() > 1); + emit backwardAvailable(d->stack.size() > 1); emit forwardAvailable(true); emit historyChanged(); } @@ -1156,7 +1156,7 @@ QVariant QTextBrowser::loadResource(int /*type*/, const QUrl &name) bool QTextBrowser::isBackwardAvailable() const { Q_D(const QTextBrowser); - return d->stack.count() > 1; + return d->stack.size() > 1; } /*! @@ -1243,7 +1243,7 @@ QString QTextBrowser::historyTitle(int i) const int QTextBrowser::forwardHistoryCount() const { Q_D(const QTextBrowser); - return d->forwardStack.count(); + return d->forwardStack.size(); } /*! @@ -1254,7 +1254,7 @@ int QTextBrowser::forwardHistoryCount() const int QTextBrowser::backwardHistoryCount() const { Q_D(const QTextBrowser); - return d->stack.count()-1; + return d->stack.size()-1; } /*! diff --git a/src/widgets/widgets/qtextedit.cpp b/src/widgets/widgets/qtextedit.cpp index b3a8963431..f3d1d3e511 100644 --- a/src/widgets/widgets/qtextedit.cpp +++ b/src/widgets/widgets/qtextedit.cpp @@ -1371,7 +1371,7 @@ void QTextEdit::keyPressEvent(QKeyEvent *e) const QString text = e->text(); if (cursor.atBlockStart() && (d->autoFormatting & AutoBulletList) - && (text.length() == 1) + && (text.size() == 1) && (text.at(0) == u'-' || text.at(0) == u'*') && (!cursor.currentList())) { diff --git a/src/widgets/widgets/qtoolbararealayout.cpp b/src/widgets/widgets/qtoolbararealayout.cpp index adddfbc529..54c21b6038 100644 --- a/src/widgets/widgets/qtoolbararealayout.cpp +++ b/src/widgets/widgets/qtoolbararealayout.cpp @@ -70,7 +70,7 @@ QToolBarAreaLayoutLine::QToolBarAreaLayoutLine(Qt::Orientation orientation) QSize QToolBarAreaLayoutLine::sizeHint() const { int a = 0, b = 0; - for (int i = 0; i < toolBarItems.count(); ++i) { + for (int i = 0; i < toolBarItems.size(); ++i) { const QToolBarAreaLayoutItem &item = toolBarItems.at(i); if (item.skip()) continue; @@ -90,7 +90,7 @@ QSize QToolBarAreaLayoutLine::sizeHint() const QSize QToolBarAreaLayoutLine::minimumSize() const { int a = 0, b = 0; - for (int i = 0; i < toolBarItems.count(); ++i) { + for (int i = 0; i < toolBarItems.size(); ++i) { const QToolBarAreaLayoutItem &item = toolBarItems[i]; if (item.skip()) continue; @@ -114,7 +114,7 @@ void QToolBarAreaLayoutLine::fitLayout() int space = pick(o, rect.size()); int extra = qMax(0, space - min); - for (int i = 0; i < toolBarItems.count(); ++i) { + for (int i = 0; i < toolBarItems.size(); ++i) { QToolBarAreaLayoutItem &item = toolBarItems[i]; if (item.skip()) continue; @@ -137,7 +137,7 @@ void QToolBarAreaLayoutLine::fitLayout() // calculate the positions from the sizes int pos = 0; - for (int i = 0; i < toolBarItems.count(); ++i) { + for (int i = 0; i < toolBarItems.size(); ++i) { QToolBarAreaLayoutItem &item = toolBarItems[i]; if (item.skip()) continue; @@ -151,7 +151,7 @@ void QToolBarAreaLayoutLine::fitLayout() bool QToolBarAreaLayoutLine::skip() const { - for (int i = 0; i < toolBarItems.count(); ++i) { + for (int i = 0; i < toolBarItems.size(); ++i) { if (!toolBarItems.at(i).skip()) return false; } @@ -183,7 +183,7 @@ QToolBarAreaLayoutInfo::QToolBarAreaLayoutInfo(QInternal::DockPosition pos) QSize QToolBarAreaLayoutInfo::sizeHint() const { int a = 0, b = 0; - for (int i = 0; i < lines.count(); ++i) { + for (int i = 0; i < lines.size(); ++i) { const QToolBarAreaLayoutLine &l = lines.at(i); if (l.skip()) continue; @@ -203,7 +203,7 @@ QSize QToolBarAreaLayoutInfo::sizeHint() const QSize QToolBarAreaLayoutInfo::minimumSize() const { int a = 0, b = 0; - for (int i = 0; i < lines.count(); ++i) { + for (int i = 0; i < lines.size(); ++i) { const QToolBarAreaLayoutLine &l = lines.at(i); if (l.skip()) continue; @@ -228,9 +228,9 @@ void QToolBarAreaLayoutInfo::fitLayout() bool reverse = dockPos == QInternal::RightDock || dockPos == QInternal::BottomDock; - int i = reverse ? lines.count() - 1 : 0; + int i = reverse ? lines.size() - 1 : 0; for (;;) { - if ((reverse && i < 0) || (!reverse && i == lines.count())) + if ((reverse && i < 0) || (!reverse && i == lines.size())) break; QToolBarAreaLayoutLine &l = lines[i]; @@ -273,10 +273,10 @@ void QToolBarAreaLayoutInfo::insertItem(QToolBar *before, QLayoutItem *item) return; } - for (int j = 0; j < lines.count(); ++j) { + for (int j = 0; j < lines.size(); ++j) { QToolBarAreaLayoutLine &line = lines[j]; - for (int k = 0; k < line.toolBarItems.count(); ++k) { + for (int k = 0; k < line.toolBarItems.size(); ++k) { if (line.toolBarItems.at(k).widgetItem->widget() == before) { line.toolBarItems.insert(k, item); return; @@ -287,17 +287,17 @@ void QToolBarAreaLayoutInfo::insertItem(QToolBar *before, QLayoutItem *item) void QToolBarAreaLayoutInfo::removeToolBar(QToolBar *toolBar) { - for (int j = 0; j < lines.count(); ++j) { + for (int j = 0; j < lines.size(); ++j) { QToolBarAreaLayoutLine &line = lines[j]; - for (int k = 0; k < line.toolBarItems.count(); ++k) { + for (int k = 0; k < line.toolBarItems.size(); ++k) { QToolBarAreaLayoutItem &item = line.toolBarItems[k]; if (item.widgetItem->widget() == toolBar) { delete item.widgetItem; item.widgetItem = nullptr; line.toolBarItems.removeAt(k); - if (line.toolBarItems.isEmpty() && j < lines.count() - 1) + if (line.toolBarItems.isEmpty() && j < lines.size() - 1) lines.removeAt(j); return; @@ -315,10 +315,10 @@ void QToolBarAreaLayoutInfo::insertToolBarBreak(QToolBar *before) return; } - for (int j = 0; j < lines.count(); ++j) { + for (int j = 0; j < lines.size(); ++j) { QToolBarAreaLayoutLine &line = lines[j]; - for (int k = 0; k < line.toolBarItems.count(); ++k) { + for (int k = 0; k < line.toolBarItems.size(); ++k) { if (line.toolBarItems.at(k).widgetItem->widget() == before) { if (k == 0) return; @@ -336,10 +336,10 @@ void QToolBarAreaLayoutInfo::insertToolBarBreak(QToolBar *before) void QToolBarAreaLayoutInfo::removeToolBarBreak(QToolBar *before) { - for (int j = 0; j < lines.count(); ++j) { + for (int j = 0; j < lines.size(); ++j) { const QToolBarAreaLayoutLine &line = lines.at(j); - for (int k = 0; k < line.toolBarItems.count(); ++k) { + for (int k = 0; k < line.toolBarItems.size(); ++k) { if (line.toolBarItems.at(k).widgetItem->widget() == before) { if (k != 0) return; @@ -366,12 +366,12 @@ void QToolBarAreaLayoutInfo::moveToolBar(QToolBar *toolbar, int pos) pos -= rect.top(); //here we actually update the preferredSize for the line containing the toolbar so that we move it - for (int j = 0; j < lines.count(); ++j) { + for (int j = 0; j < lines.size(); ++j) { QToolBarAreaLayoutLine &line = lines[j]; int previousIndex = -1; int minPos = 0; - for (int k = 0; k < line.toolBarItems.count(); ++k) { + for (int k = 0; k < line.toolBarItems.size(); ++k) { QToolBarAreaLayoutItem ¤t = line.toolBarItems[k]; if (current.widgetItem->widget() == toolbar) { int newPos = current.pos; @@ -383,7 +383,7 @@ void QToolBarAreaLayoutInfo::moveToolBar(QToolBar *toolbar, int pos) } else { //we check the max value for the position (until everything at the right is "compressed") int maxPos = pick(o, rect.size()); - for(int l = k; l < line.toolBarItems.count(); ++l) { + for(int l = k; l < line.toolBarItems.size(); ++l) { const QToolBarAreaLayoutItem &item = line.toolBarItems.at(l); if (!item.skip()) { maxPos -= pick(o, item.minimumSize()); @@ -451,7 +451,7 @@ QList<int> QToolBarAreaLayoutInfo::gapIndex(const QPoint &pos, int *minDistance) // Since we're comparing p with item.pos, we put them in the same coordinate system. const int p = pick(o, pos - rect.topLeft()); - for (int j = 0; j < lines.count(); ++j) { + for (int j = 0; j < lines.size(); ++j) { const QToolBarAreaLayoutLine &line = lines.at(j); if (line.skip()) continue; @@ -459,7 +459,7 @@ QList<int> QToolBarAreaLayoutInfo::gapIndex(const QPoint &pos, int *minDistance) continue; int k = 0; - for (; k < line.toolBarItems.count(); ++k) { + for (; k < line.toolBarItems.size(); ++k) { const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k); if (item.skip()) continue; @@ -485,7 +485,7 @@ QList<int> QToolBarAreaLayoutInfo::gapIndex(const QPoint &pos, int *minDistance) *minDistance = dist; QList<int> result; - result << lines.count() << 0; + result << lines.size() << 0; return result; } } @@ -495,9 +495,9 @@ QList<int> QToolBarAreaLayoutInfo::gapIndex(const QPoint &pos, int *minDistance) bool QToolBarAreaLayoutInfo::insertGap(const QList<int> &path, QLayoutItem *item) { - Q_ASSERT(path.count() == 2); + Q_ASSERT(path.size() == 2); int j = path.first(); - if (j == lines.count()) + if (j == lines.size()) lines.append(QToolBarAreaLayoutLine(o)); QToolBarAreaLayoutLine &line = lines[j]; @@ -540,7 +540,7 @@ void QToolBarAreaLayoutInfo::clear() QRect QToolBarAreaLayoutInfo::itemRect(const QList<int> &path) const { - Q_ASSERT(path.count() == 2); + Q_ASSERT(path.size() == 2); int j = path.at(0); int k = path.at(1); @@ -698,10 +698,10 @@ QLayoutItem *QToolBarAreaLayout::itemAt(int *x, int index) const for (int i = 0; i < QInternal::DockCount; ++i) { const QToolBarAreaLayoutInfo &dock = docks[i]; - for (int j = 0; j < dock.lines.count(); ++j) { + for (int j = 0; j < dock.lines.size(); ++j) { const QToolBarAreaLayoutLine &line = dock.lines.at(j); - for (int k = 0; k < line.toolBarItems.count(); ++k) { + for (int k = 0; k < line.toolBarItems.size(); ++k) { if ((*x)++ == index) return line.toolBarItems.at(k).widgetItem; } @@ -718,10 +718,10 @@ QLayoutItem *QToolBarAreaLayout::takeAt(int *x, int index) for (int i = 0; i < QInternal::DockCount; ++i) { QToolBarAreaLayoutInfo &dock = docks[i]; - for (int j = 0; j < dock.lines.count(); ++j) { + for (int j = 0; j < dock.lines.size(); ++j) { QToolBarAreaLayoutLine &line = dock.lines[j]; - for (int k = 0; k < line.toolBarItems.count(); ++k) { + for (int k = 0; k < line.toolBarItems.size(); ++k) { if ((*x)++ == index) { QLayoutItem *result = line.toolBarItems.takeAt(k).widgetItem; if (line.toolBarItems.isEmpty()) @@ -740,10 +740,10 @@ void QToolBarAreaLayout::deleteAllLayoutItems() for (int i = 0; i < QInternal::DockCount; ++i) { QToolBarAreaLayoutInfo &dock = docks[i]; - for (int j = 0; j < dock.lines.count(); ++j) { + for (int j = 0; j < dock.lines.size(); ++j) { QToolBarAreaLayoutLine &line = dock.lines[j]; - for (int k = 0; k < line.toolBarItems.count(); ++k) { + for (int k = 0; k < line.toolBarItems.size(); ++k) { QToolBarAreaLayoutItem &item = line.toolBarItems[k]; if (!item.gap) delete item.widgetItem; @@ -758,10 +758,10 @@ QInternal::DockPosition QToolBarAreaLayout::findToolBar(const QToolBar *toolBar) for (int i = 0; i < QInternal::DockCount; ++i) { const QToolBarAreaLayoutInfo &dock = docks[i]; - for (int j = 0; j < dock.lines.count(); ++j) { + for (int j = 0; j < dock.lines.size(); ++j) { const QToolBarAreaLayoutLine &line = dock.lines.at(j); - for (int k = 0; k < line.toolBarItems.count(); ++k) { + for (int k = 0; k < line.toolBarItems.size(); ++k) { if (line.toolBarItems.at(k).widgetItem->widget() == toolBar) return static_cast<QInternal::DockPosition>(i); } @@ -849,12 +849,12 @@ void QToolBarAreaLayout::apply(bool animate) for (int i = 0; i < QInternal::DockCount; ++i) { const QToolBarAreaLayoutInfo &dock = docks[i]; - for (int j = 0; j < dock.lines.count(); ++j) { + for (int j = 0; j < dock.lines.size(); ++j) { const QToolBarAreaLayoutLine &line = dock.lines.at(j); if (line.skip()) continue; - for (int k = 0; k < line.toolBarItems.count(); ++k) { + for (int k = 0; k < line.toolBarItems.size(); ++k) { const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k); if (item.skip() || item.gap) continue; @@ -907,10 +907,10 @@ bool QToolBarAreaLayout::toolBarBreak(QToolBar *toolBar) const for (int i = 0; i < QInternal::DockCount; ++i) { const QToolBarAreaLayoutInfo &dock = docks[i]; - for (int j = 0; j < dock.lines.count(); ++j) { + for (int j = 0; j < dock.lines.size(); ++j) { const QToolBarAreaLayoutLine &line = dock.lines.at(j); - for (int k = 0; k < line.toolBarItems.count(); ++k) { + for (int k = 0; k < line.toolBarItems.size(); ++k) { if (line.toolBarItems.at(k).widgetItem->widget() == toolBar) return j > 0 && k == 0; } @@ -925,25 +925,25 @@ void QToolBarAreaLayout::getStyleOptionInfo(QStyleOptionToolBar *option, QToolBa for (int i = 0; i < QInternal::DockCount; ++i) { const QToolBarAreaLayoutInfo &dock = docks[i]; - for (int j = 0; j < dock.lines.count(); ++j) { + for (int j = 0; j < dock.lines.size(); ++j) { const QToolBarAreaLayoutLine &line = dock.lines.at(j); - for (int k = 0; k < line.toolBarItems.count(); ++k) { + for (int k = 0; k < line.toolBarItems.size(); ++k) { if (line.toolBarItems.at(k).widgetItem->widget() == toolBar) { - if (line.toolBarItems.count() == 1) + if (line.toolBarItems.size() == 1) option->positionWithinLine = QStyleOptionToolBar::OnlyOne; else if (k == 0) option->positionWithinLine = QStyleOptionToolBar::Beginning; - else if (k == line.toolBarItems.count() - 1) + else if (k == line.toolBarItems.size() - 1) option->positionWithinLine = QStyleOptionToolBar::End; else option->positionWithinLine = QStyleOptionToolBar::Middle; - if (dock.lines.count() == 1) + if (dock.lines.size() == 1) option->positionOfLine = QStyleOptionToolBar::OnlyOne; else if (j == 0) option->positionOfLine = QStyleOptionToolBar::Beginning; - else if (j == dock.lines.count() - 1) + else if (j == dock.lines.size() - 1) option->positionOfLine = QStyleOptionToolBar::End; else option->positionOfLine = QStyleOptionToolBar::Middle; @@ -964,10 +964,10 @@ QList<int> QToolBarAreaLayout::indexOf(QWidget *toolBar) const for (int i = 0; i < QInternal::DockCount; ++i) { const QToolBarAreaLayoutInfo &dock = docks[i]; - for (int j = 0; j < dock.lines.count(); ++j) { + for (int j = 0; j < dock.lines.size(); ++j) { const QToolBarAreaLayoutLine &line = dock.lines.at(j); - for (int k = 0; k < line.toolBarItems.count(); ++k) { + for (int k = 0; k < line.toolBarItems.size(); ++k) { const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k); if (!item.gap && item.widgetItem->widget() == toolBar) { found = true; @@ -1016,10 +1016,10 @@ QList<int> QToolBarAreaLayout::currentGapIndex() const for (int i = 0; i < QInternal::DockCount; ++i) { const QToolBarAreaLayoutInfo &dock = docks[i]; - for (int j = 0; j < dock.lines.count(); ++j) { + for (int j = 0; j < dock.lines.size(); ++j) { const QToolBarAreaLayoutLine &line = dock.lines[j]; - for (int k = 0; k < line.toolBarItems.count(); k++) { + for (int k = 0; k < line.toolBarItems.size(); k++) { if (line.toolBarItems[k].gap) { QList<int> result; result << i << j << k; @@ -1033,7 +1033,7 @@ QList<int> QToolBarAreaLayout::currentGapIndex() const bool QToolBarAreaLayout::insertGap(const QList<int> &path, QLayoutItem *item) { - Q_ASSERT(path.count() == 3); + Q_ASSERT(path.size() == 3); const int i = path.first(); Q_ASSERT(i >= 0 && i < QInternal::DockCount); return docks[i].insertGap(path.mid(1), item); @@ -1041,7 +1041,7 @@ bool QToolBarAreaLayout::insertGap(const QList<int> &path, QLayoutItem *item) void QToolBarAreaLayout::remove(const QList<int> &path) { - Q_ASSERT(path.count() == 3); + Q_ASSERT(path.size() == 3); QToolBarAreaLayoutInfo &dock = docks[path.at(0)]; QToolBarAreaLayoutLine &line = dock.lines[path.at(1)]; line.toolBarItems.removeAt(path.at(2)); @@ -1054,10 +1054,10 @@ void QToolBarAreaLayout::remove(QLayoutItem *item) for (int i = 0; i < QInternal::DockCount; ++i) { QToolBarAreaLayoutInfo &dock = docks[i]; - for (int j = 0; j < dock.lines.count(); ++j) { + for (int j = 0; j < dock.lines.size(); ++j) { QToolBarAreaLayoutLine &line = dock.lines[j]; - for (int k = 0; k < line.toolBarItems.count(); k++) { + for (int k = 0; k < line.toolBarItems.size(); k++) { if (line.toolBarItems[k].widgetItem == item) { line.toolBarItems.removeAt(k); if (line.toolBarItems.isEmpty()) @@ -1078,15 +1078,15 @@ void QToolBarAreaLayout::clear() QToolBarAreaLayoutItem *QToolBarAreaLayout::item(const QList<int> &path) { - Q_ASSERT(path.count() == 3); + Q_ASSERT(path.size() == 3); if (path.at(0) < 0 || path.at(0) >= QInternal::DockCount) return nullptr; QToolBarAreaLayoutInfo &info = docks[path.at(0)]; - if (path.at(1) < 0 || path.at(1) >= info.lines.count()) + if (path.at(1) < 0 || path.at(1) >= info.lines.size()) return nullptr; QToolBarAreaLayoutLine &line = info.lines[path.at(1)]; - if (path.at(2) < 0 || path.at(2) >= line.toolBarItems.count()) + if (path.at(2) < 0 || path.at(2) >= line.toolBarItems.size()) return nullptr; return &(line.toolBarItems[path.at(2)]); } @@ -1118,7 +1118,7 @@ QLayoutItem *QToolBarAreaLayout::plug(const QList<int> &path) QLayoutItem *QToolBarAreaLayout::unplug(const QList<int> &path, QToolBarAreaLayout *other) { //other needs to be update as well - Q_ASSERT(path.count() == 3); + Q_ASSERT(path.size() == 3); QToolBarAreaLayoutItem *item = this->item(path); Q_ASSERT(item); @@ -1136,7 +1136,7 @@ QLayoutItem *QToolBarAreaLayout::unplug(const QList<int> &path, QToolBarAreaLayo if (!previous.skip()) { //we need to check if it has a previous element and a next one //the previous will get its size changed - for (int j = path.at(2) + 1; j < line.toolBarItems.count(); ++j) { + for (int j = path.at(2) + 1; j < line.toolBarItems.size(); ++j) { const QToolBarAreaLayoutItem &next = line.toolBarItems.at(j); if (!next.skip()) { newExtraSpace = next.pos - previous.pos - pick(line.o, previous.sizeHint()); @@ -1221,19 +1221,19 @@ void QToolBarAreaLayout::saveState(QDataStream &stream) const int lineCount = 0; for (int i = 0; i < QInternal::DockCount; ++i) - lineCount += docks[i].lines.count(); + lineCount += docks[i].lines.size(); stream << lineCount; for (int i = 0; i < QInternal::DockCount; ++i) { const QToolBarAreaLayoutInfo &dock = docks[i]; - for (int j = 0; j < dock.lines.count(); ++j) { + for (int j = 0; j < dock.lines.size(); ++j) { const QToolBarAreaLayoutLine &line = dock.lines.at(j); - stream << i << int(line.toolBarItems.count()); + stream << i << int(line.toolBarItems.size()); - for (int k = 0; k < line.toolBarItems.count(); ++k) { + for (int k = 0; k < line.toolBarItems.size(); ++k) { const QToolBarAreaLayoutItem &item = line.toolBarItems.at(k); QWidget *widget = const_cast<QLayoutItem*>(item.widgetItem)->widget(); QString objectName = widget->objectName(); @@ -1317,7 +1317,7 @@ bool QToolBarAreaLayout::restoreState(QDataStream &stream, const QList<QToolBar* } QToolBar *toolBar = nullptr; - for (int x = 0; x < toolBars.count(); ++x) { + for (int x = 0; x < toolBars.size(); ++x) { if (toolBars.at(x)->objectName() == objectName) { toolBar = toolBars.takeAt(x); break; @@ -1335,7 +1335,7 @@ bool QToolBarAreaLayout::restoreState(QDataStream &stream, const QList<QToolBar* item.widgetItem = new QWidgetItemV2(toolBar); toolBar->setOrientation(floating ? ((shown & 2) ? Qt::Vertical : Qt::Horizontal) : dock.o); toolBar->setVisible(shown & 1); - toolBar->d_func()->setWindowState(floating, true, rect); + toolBar->d_func()->setWindowState(floating, false, rect); item.preferredSize = item.size; line.toolBarItems.append(item); diff --git a/src/widgets/widgets/qtoolbarlayout.cpp b/src/widgets/widgets/qtoolbarlayout.cpp index ebfece96d0..cc842e2657 100644 --- a/src/widgets/widgets/qtoolbarlayout.cpp +++ b/src/widgets/widgets/qtoolbarlayout.cpp @@ -132,14 +132,14 @@ void QToolBarLayout::addItem(QLayoutItem*) QLayoutItem *QToolBarLayout::itemAt(int index) const { - if (index < 0 || index >= items.count()) + if (index < 0 || index >= items.size()) return nullptr; return items.at(index); } QLayoutItem *QToolBarLayout::takeAt(int index) { - if (index < 0 || index >= items.count()) + if (index < 0 || index >= items.size()) return nullptr; QToolBarItem *item = items.takeAt(index); @@ -162,7 +162,7 @@ QLayoutItem *QToolBarLayout::takeAt(int index) void QToolBarLayout::insertAction(int index, QAction *action) { index = qMax(0, index); - index = qMin(items.count(), index); + index = qMin(items.size(), index); QToolBarItem *item = createItem(action); if (item) { @@ -173,7 +173,7 @@ void QToolBarLayout::insertAction(int index, QAction *action) int QToolBarLayout::indexOf(const QAction *action) const { - for (int i = 0; i < items.count(); ++i) { + for (int i = 0; i < items.size(); ++i) { if (items.at(i)->action == action) return i; } @@ -182,7 +182,7 @@ int QToolBarLayout::indexOf(const QAction *action) const int QToolBarLayout::count() const { - return items.count(); + return items.size(); } bool QToolBarLayout::isEmpty() const @@ -246,10 +246,10 @@ void QToolBarLayout::updateGeomArray() const that->expanding = false; that->empty = false; - QList<QLayoutStruct> a(items.count() + 1); // + 1 for the stretch + QList<QLayoutStruct> a(items.size() + 1); // + 1 for the stretch int count = 0; - for (int i = 0; i < items.count(); ++i) { + for (int i = 0; i < items.size(); ++i) { QToolBarItem *item = items.at(i); QSize max = item->maximumSize(); @@ -296,7 +296,7 @@ void QToolBarLayout::updateGeomArray() const rpick(o, that->minSize) += handleExtent; that->minSize += QSize(pick(Qt::Horizontal, margins), pick(Qt::Vertical, margins)); - if (items.count() > 1) + if (items.size() > 1) rpick(o, that->minSize) += spacing + extensionExtent; rpick(o, that->hint) += handleExtent; @@ -431,7 +431,7 @@ bool QToolBarLayout::layoutActions(const QSize &size) int rows = 0; int rowPos = perp(o, rect.topLeft()) + perp(o, QSize(margins.top(), margins.left())); int i = 0; - while (i < items.count()) { + while (i < items.size()) { QList<QLayoutStruct> a = geomArray; int start = i; @@ -441,7 +441,7 @@ bool QToolBarLayout::layoutActions(const QSize &size) int count = 0; int maximumSize = 0; bool expansiveRow = false; - for (; i < items.count(); ++i) { + for (; i < items.size(); ++i) { if (a[i].empty) continue; @@ -512,7 +512,7 @@ bool QToolBarLayout::layoutActions(const QSize &size) } if (!expanded) { - for (int j = i; j < items.count(); ++j) { + for (int j = i; j < items.size(); ++j) { QToolBarItem *item = items.at(j); if (!item->widget()->isHidden()) hideWidgets << item->widget(); @@ -537,9 +537,9 @@ bool QToolBarLayout::layoutActions(const QSize &size) extension->setEnabled(popupMenu == nullptr || !extensionMenuContainsOnlyWidgetActions); // we have to do the show/hide here, because it triggers more calls to setGeometry :( - for (int i = 0; i < showWidgets.count(); ++i) + for (int i = 0; i < showWidgets.size(); ++i) showWidgets.at(i)->show(); - for (int i = 0; i < hideWidgets.count(); ++i) + for (int i = 0; i < hideWidgets.size(); ++i) hideWidgets.at(i)->hide(); return ranOutOfSpace; @@ -566,7 +566,7 @@ QSize QToolBarLayout::expandedSize(const QSize &size) const int total_w = 0; int count = 0; - for (int x = 0; x < items.count(); ++x) { + for (int x = 0; x < items.size(); ++x) { if (!geomArray[x].empty) { total_w += (count == 0 ? 0 : spacing) + geomArray[x].minimumSize; ++count; @@ -587,12 +587,12 @@ QSize QToolBarLayout::expandedSize(const QSize &size) const int w = 0; int h = 0; int i = 0; - while (i < items.count()) { + while (i < items.size()) { int count = 0; int size = 0; int prev = -1; int rowHeight = 0; - for (; i < items.count(); ++i) { + for (; i < items.size(); ++i) { if (geomArray[i].empty) continue; diff --git a/src/widgets/widgets/qwidgetlinecontrol.cpp b/src/widgets/widgets/qwidgetlinecontrol.cpp index e95509ae89..30465b95fa 100644 --- a/src/widgets/widgets/qwidgetlinecontrol.cpp +++ b/src/widgets/widgets/qwidgetlinecontrol.cpp @@ -62,7 +62,7 @@ void QWidgetLineControl::updateDisplayText(bool forceUpdate) if (m_echoMode == QLineEdit::Password) { str.fill(m_passwordCharacter); - if (m_passwordEchoTimer != 0 && m_cursor > 0 && m_cursor <= m_text.length()) { + if (m_passwordEchoTimer != 0 && m_cursor > 0 && m_cursor <= m_text.size()) { int cursor = m_cursor - 1; QChar uc = m_text.at(cursor); str[cursor] = uc; @@ -82,7 +82,7 @@ void QWidgetLineControl::updateDisplayText(bool forceUpdate) // drawing boxes when using fonts that don't have glyphs for such // characters) QChar* uc = str.data(); - for (int i = 0; i < (int)str.length(); ++i) { + for (int i = 0; i < (int)str.size(); ++i) { if ((uc[i].unicode() < 0x20 && uc[i].unicode() != 0x09) || uc[i] == QChar::LineSeparator || uc[i] == QChar::ParagraphSeparator @@ -242,7 +242,7 @@ void QWidgetLineControl::clear() { int priorState = m_undoState; m_selstart = 0; - m_selend = m_text.length(); + m_selend = m_text.size(); removeSelectedText(); separate(); finishChange(priorState, /*update*/false, /*edited*/false); @@ -286,7 +286,7 @@ void QWidgetLineControl::setSelection(int start, int length) if (start == m_selstart && start + length == m_selend && m_cursor == m_selend) return; m_selstart = start; - m_selend = qMin(start + length, (int)m_text.length()); + m_selend = qMin(start + length, (int)m_text.size()); m_cursor = m_selend; } else if (length < 0){ if (start == m_selend && start + length == m_selstart && m_cursor == m_selstart) @@ -329,7 +329,7 @@ void QWidgetLineControl::init(const QString &txt) m_textLayout.setCacheEnabled(true); m_text = txt; updateDisplayText(); - m_cursor = m_text.length(); + m_cursor = m_text.size(); if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) { m_keyboardScheme = theme->themeHint(QPlatformTheme::KeyboardScheme).toInt(); m_passwordMaskDelay = theme->themeHint(QPlatformTheme::PasswordMaskDelay).toInt(); @@ -491,14 +491,14 @@ void QWidgetLineControl::processInputMethodEvent(QInputMethodEvent *event) if (echoMode() == QLineEdit::PasswordEchoOnEdit && !passwordEchoEditing()) { updatePasswordEchoEditing(true); m_selstart = 0; - m_selend = m_text.length(); + m_selend = m_text.size(); } removeSelectedText(); } int c = m_cursor; // cursor position after insertion of commit string if (event->replacementStart() <= 0) - c += event->commitString().length() - qMin(-event->replacementStart(), event->replacementLength()); + c += event->commitString().size() - qMin(-event->replacementStart(), event->replacementLength()); m_cursor += event->replacementStart(); if (m_cursor < 0) @@ -514,15 +514,15 @@ void QWidgetLineControl::processInputMethodEvent(QInputMethodEvent *event) internalInsert(event->commitString()); cursorPositionChanged = true; } else { - m_cursor = qBound(0, c, m_text.length()); + m_cursor = qBound(0, c, m_text.size()); } for (int i = 0; i < event->attributes().size(); ++i) { const QInputMethodEvent::Attribute &a = event->attributes().at(i); if (a.type == QInputMethodEvent::Selection) { - m_cursor = qBound(0, a.start + a.length, m_text.length()); + m_cursor = qBound(0, a.start + a.length, m_text.size()); if (a.length) { - m_selstart = qMax(0, qMin(a.start, m_text.length())); + m_selstart = qMax(0, qMin(a.start, m_text.size())); m_selend = m_cursor; if (m_selend < m_selstart) { qSwap(m_selstart, m_selend); @@ -554,7 +554,7 @@ void QWidgetLineControl::processInputMethodEvent(QInputMethodEvent *event) } #endif //QT_NO_IM const int oldPreeditCursor = m_preeditCursor; - m_preeditCursor = event->preeditString().length(); + m_preeditCursor = event->preeditString().size(); m_hideCursor = false; QList<QTextLayout::FormatRange> formats; formats.reserve(event->attributes().size()); @@ -695,7 +695,7 @@ bool QWidgetLineControl::finishChange(int validateFromState, bool update, bool e } #endif if (validateFromState >= 0 && wasValidInput && !m_validInput) { - if (m_transactions.count()) + if (m_transactions.size()) return false; internalUndo(validateFromState); m_history.erase(m_history.begin() + m_undoState, m_history.end()); @@ -737,7 +737,7 @@ void QWidgetLineControl::internalSetText(const QString &txt, int pos, bool edite QString oldText = m_text; if (m_maskData) { m_text = maskString(0, txt, true); - m_text += clearString(m_text.length(), m_maxLength - m_text.length()); + m_text += clearString(m_text.size(), m_maxLength - m_text.size()); if (edited && oldText == m_text) emit inputRejected(); } else { @@ -745,7 +745,7 @@ void QWidgetLineControl::internalSetText(const QString &txt, int pos, bool edite } m_history.clear(); m_modifiedState = m_undoState = 0; - m_cursor = (pos < 0 || pos > m_text.length()) ? m_text.length() : pos; + m_cursor = (pos < 0 || pos > m_text.size()) ? m_text.size() : pos; m_textDirty = (oldText != m_text); const bool changed = finishChange(-1, true, edited); @@ -823,12 +823,12 @@ void QWidgetLineControl::internalInsert(const QString &s) QAccessibleTextInsertEvent insertEvent(accessibleObject(), m_cursor, ms); QAccessible::updateAccessibility(&insertEvent); #endif - for (int i = 0; i < (int) ms.length(); ++i) { + for (int i = 0; i < (int) ms.size(); ++i) { addCommand (Command(DeleteSelection, m_cursor + i, m_text.at(m_cursor + i), -1, -1)); addCommand(Command(Insert, m_cursor + i, ms.at(i), -1, -1)); } - m_text.replace(m_cursor, ms.length(), ms); - m_cursor += ms.length(); + m_text.replace(m_cursor, ms.size(), ms); + m_cursor += ms.size(); m_cursor = nextMaskBlank(m_cursor); m_textDirty = true; #if QT_CONFIG(accessibility) @@ -836,18 +836,18 @@ void QWidgetLineControl::internalInsert(const QString &s) QAccessible::updateAccessibility(&event); #endif } else { - int remaining = m_maxLength - m_text.length(); + int remaining = m_maxLength - m_text.size(); if (remaining != 0) { #if QT_CONFIG(accessibility) QAccessibleTextInsertEvent insertEvent(accessibleObject(), m_cursor, s); QAccessible::updateAccessibility(&insertEvent); #endif m_text.insert(m_cursor, s.left(remaining)); - for (int i = 0; i < (int) s.left(remaining).length(); ++i) + for (int i = 0; i < (int) s.left(remaining).size(); ++i) addCommand(Command(Insert, m_cursor++, s.at(i), -1, -1)); m_textDirty = true; } - if (s.length() > remaining) + if (s.size() > remaining) emit inputRejected(); } } @@ -865,7 +865,7 @@ void QWidgetLineControl::internalInsert(const QString &s) */ void QWidgetLineControl::internalDelete(bool wasBackspace) { - if (m_cursor < (int) m_text.length()) { + if (m_cursor < (int) m_text.size()) { cancelPasswordEchoTimer(); if (hasSelectedText()) addCommand(Command(SetSelection, m_cursor, u'\0', m_selstart, m_selend)); @@ -896,7 +896,7 @@ void QWidgetLineControl::internalDelete(bool wasBackspace) */ void QWidgetLineControl::removeSelectedText() { - if (m_selstart < m_selend && m_selend <= (int) m_text.length()) { + if (m_selstart < m_selend && m_selend <= (int) m_text.size()) { cancelPasswordEchoTimer(); separate(); int i ; @@ -953,13 +953,13 @@ void QWidgetLineControl::parseInputMask(const QString &maskFields) m_inputMask = maskFields; } else { m_inputMask = maskFields.left(delimiter); - m_blank = (delimiter + 1 < maskFields.length()) ? maskFields[delimiter + 1] : u' '; + m_blank = (delimiter + 1 < maskFields.size()) ? maskFields[delimiter + 1] : u' '; } // calculate m_maxLength / m_maskData length m_maxLength = 0; bool escaped = false; - for (int i=0; i<m_inputMask.length(); i++) { + for (int i=0; i<m_inputMask.size(); i++) { const auto c = m_inputMask.at(i); if (escaped) { ++m_maxLength; @@ -983,7 +983,7 @@ void QWidgetLineControl::parseInputMask(const QString &maskFields) bool s; bool escape = false; int index = 0; - for (int i = 0; i < m_inputMask.length(); i++) { + for (int i = 0; i < m_inputMask.size(); i++) { const auto c = m_inputMask.at(i); if (escape) { s = true; @@ -1132,7 +1132,7 @@ bool QWidgetLineControl::hasAcceptableInput(const QString &str) const if (!m_maskData) return true; - if (str.length() != m_maxLength) + if (str.size() != m_maxLength) return false; for (int i=0; i < m_maxLength; ++i) { @@ -1167,7 +1167,7 @@ QString QWidgetLineControl::maskString(int pos, const QString &str, bool clear) QString s = QString::fromLatin1(""); int i = pos; while (i < m_maxLength) { - if (strIndex < str.length()) { + if (strIndex < str.size()) { if (m_maskData[i].separator) { s += m_maskData[i].maskChar; if (str[strIndex] == m_maskData[i].maskChar) @@ -1190,7 +1190,7 @@ QString QWidgetLineControl::maskString(int pos, const QString &str, bool clear) // search for separator first int n = findInMask(i, true, true, str[strIndex]); if (n != -1) { - if (str.length() != 1 || i == 0 || (i > 0 && (!m_maskData[i-1].separator || m_maskData[i-1].maskChar != str[strIndex]))) { + if (str.size() != 1 || i == 0 || (i > 0 && (!m_maskData[i-1].separator || m_maskData[i-1].maskChar != str[strIndex]))) { s += QStringView{fill}.mid(i, n - i + 1); i = n + 1; // update i to find + 1 } @@ -1258,7 +1258,7 @@ QString QWidgetLineControl::stripString(const QString &str) const return str; QString s; - int end = qMin(m_maxLength, (int)str.length()); + int end = qMin(m_maxLength, (int)str.size()); for (int i = 0; i < end; ++i) if (m_maskData[i].separator) s += m_maskData[i].maskChar; @@ -1445,7 +1445,7 @@ void QWidgetLineControl::complete(int key) return; int n = 0; if (key == Qt::Key_Up || key == Qt::Key_Down) { - if (textAfterSelection().length()) + if (textAfterSelection().size()) return; QString prefix = hasSelectedText() ? textBeforeSelection() : text; diff --git a/src/widgets/widgets/qwidgetlinecontrol_p.h b/src/widgets/widgets/qwidgetlinecontrol_p.h index eabe1d31c4..838a46fff6 100644 --- a/src/widgets/widgets/qwidgetlinecontrol_p.h +++ b/src/widgets/widgets/qwidgetlinecontrol_p.h @@ -115,7 +115,7 @@ public: bool isModified() const { return m_modifiedState != m_undoState; } void setModified(bool modified) { m_modifiedState = modified ? -1 : m_undoState; } - bool allSelected() const { return !m_text.isEmpty() && m_selstart == 0 && m_selend == (int)m_text.length(); } + bool allSelected() const { return !m_text.isEmpty() && m_selstart == 0 && m_selend == (int)m_text.size(); } bool hasSelectedText() const { return !m_text.isEmpty() && m_selend > m_selstart; } int width() const { return qRound(m_textLayout.lineAt(0).width()) + 1; } @@ -150,7 +150,7 @@ public: } int start() const { return 0; } - int end() const { return m_text.length(); } + int end() const { return m_text.size(); } #ifndef QT_NO_CLIPBOARD void copy(QClipboard::Mode mode = QClipboard::Clipboard) const; @@ -186,7 +186,7 @@ public: void cursorWordBackward(bool mark) { moveCursor(m_textLayout.previousCursorPosition(m_cursor, QTextLayout::SkipWords), mark); } void home(bool mark) { moveCursor(0, mark); } - void end(bool mark) { moveCursor(m_text.length(), mark); } + void end(bool mark) { moveCursor(m_text.size(), mark); } int xToPos(int x, QTextLine::CursorPosition = QTextLine::CursorBetweenCharacters) const; QRect rectForPos(int pos) const; @@ -231,7 +231,7 @@ public: void backspace(); void del(); void deselect() { internalDeselect(); finishChange(); } - void selectAll() { m_selstart = m_selend = m_cursor = 0; moveCursor(m_text.length(), true); } + void selectAll() { m_selstart = m_selend = m_cursor = 0; moveCursor(m_text.size(), true); } void insert(const QString &); void clear(); @@ -277,7 +277,7 @@ public: #endif int cursorPosition() const { return m_cursor; } - void setCursorPosition(int pos) { if (pos <= m_text.length()) moveCursor(qMax(0, pos)); } + void setCursorPosition(int pos) { if (pos <= m_text.size()) moveCursor(qMax(0, pos)); } bool hasAcceptableInput() const { return hasAcceptableInput(m_text); } bool fixup(); diff --git a/src/widgets/widgets/qwidgettextcontrol.cpp b/src/widgets/widgets/qwidgettextcontrol.cpp index cec18dbe69..a4679402dc 100644 --- a/src/widgets/widgets/qwidgettextcontrol.cpp +++ b/src/widgets/widgets/qwidgettextcontrol.cpp @@ -1403,7 +1403,7 @@ QRectF QWidgetTextControlPrivate::rectForPosition(int position) const if (relativePos == preeditPos) relativePos += preeditCursor; else if (relativePos > preeditPos) - relativePos += layout->preeditAreaText().length(); + relativePos += layout->preeditAreaText().size(); } QTextLine line = layout->lineForTextPosition(relativePos); @@ -1818,25 +1818,36 @@ void QWidgetTextControlPrivate::mouseReleaseEvent(QEvent *e, Qt::MouseButton but } if (interactionFlags & Qt::LinksAccessibleByMouse) { - if (!(button & Qt::LeftButton)) + + // Ignore event unless left button has been pressed + if (!(button & Qt::LeftButton)) { + e->ignore(); return; + } const QString anchor = q->anchorAt(pos); - if (anchor.isEmpty()) + // Ignore event without selection anchor + if (anchor.isEmpty()) { + e->ignore(); return; + } if (!cursor.hasSelection() || (anchor == anchorOnMousePress && hadSelectionOnMousePress)) { const int anchorPos = q->hitTest(pos, Qt::ExactHit); - if (anchorPos != -1) { - cursor.setPosition(anchorPos); - QString anchor = anchorOnMousePress; - anchorOnMousePress = QString(); - activateLinkUnderCursor(anchor); + // Ignore event without valid anchor position + if (anchorPos < 0) { + e->ignore(); + return; } + + cursor.setPosition(anchorPos); + QString anchor = anchorOnMousePress; + anchorOnMousePress = QString(); + activateLinkUnderCursor(anchor); } } } @@ -1900,7 +1911,7 @@ bool QWidgetTextControlPrivate::sendMouseEventToInputContext( QTextLayout *layout = cursor.block().layout(); int cursorPos = q->hitTest(pos, Qt::FuzzyHit) - cursor.position(); - if (cursorPos < 0 || cursorPos > layout->preeditAreaText().length()) + if (cursorPos < 0 || cursorPos > layout->preeditAreaText().size()) cursorPos = -1; if (cursorPos >= 0) { @@ -2060,7 +2071,7 @@ void QWidgetTextControlPrivate::inputMethodEvent(QInputMethodEvent *e) QList<QTextLayout::FormatRange> overrides; overrides.reserve(e->attributes().size()); const int oldPreeditCursor = preeditCursor; - preeditCursor = e->preeditString().length(); + preeditCursor = e->preeditString().size(); hideCursor = false; for (int i = 0; i < e->attributes().size(); ++i) { const QInputMethodEvent::Attribute &a = e->attributes().at(i); @@ -2095,7 +2106,7 @@ void QWidgetTextControlPrivate::inputMethodEvent(QInputMethodEvent *e) if (cursor.charFormat().isValid()) { int start = cursor.position() - block.position(); - int end = start + e->preeditString().length(); + int end = start + e->preeditString().size(); QList<QTextLayout::FormatRange>::iterator it = overrides.begin(); while (it != overrides.end()) { @@ -2168,7 +2179,7 @@ QVariant QWidgetTextControl::inputMethodQuery(Qt::InputMethodQuery property, QVa QTextCursor tmpCursor = d->cursor; int localPos = d->cursor.position() - block.position(); QString result = block.text().mid(localPos); - while (result.length() < maxLength) { + while (result.size() < maxLength) { int currentBlock = tmpCursor.blockNumber(); tmpCursor.movePosition(QTextCursor::NextBlock); if (tmpCursor.blockNumber() == currentBlock) @@ -2475,12 +2486,12 @@ void QWidgetTextControl::setExtraSelections(const QList<QTextEdit::ExtraSelectio Q_D(QWidgetTextControl); QMultiHash<int, int> hash; - for (int i = 0; i < d->extraSelections.count(); ++i) { + for (int i = 0; i < d->extraSelections.size(); ++i) { const QAbstractTextDocumentLayout::Selection &esel = d->extraSelections.at(i); hash.insert(esel.cursor.anchor(), i); } - for (int i = 0; i < selections.count(); ++i) { + for (int i = 0; i < selections.size(); ++i) { const QTextEdit::ExtraSelection &sel = selections.at(i); const auto it = hash.constFind(sel.cursor.anchor()); if (it != hash.cend()) { @@ -2509,8 +2520,8 @@ void QWidgetTextControl::setExtraSelections(const QList<QTextEdit::ExtraSelectio emit updateRequest(r); } - d->extraSelections.resize(selections.count()); - for (int i = 0; i < selections.count(); ++i) { + d->extraSelections.resize(selections.size()); + for (int i = 0; i < selections.size(); ++i) { d->extraSelections[i].cursor = selections.at(i).cursor; d->extraSelections[i].format = selections.at(i).format; } @@ -2520,7 +2531,7 @@ QList<QTextEdit::ExtraSelection> QWidgetTextControl::extraSelections() const { Q_D(const QWidgetTextControl); QList<QTextEdit::ExtraSelection> selections; - const int numExtraSelections = d->extraSelections.count(); + const int numExtraSelections = d->extraSelections.size(); selections.reserve(numExtraSelections); for (int i = 0; i < numExtraSelections; ++i) { QTextEdit::ExtraSelection sel; @@ -2699,7 +2710,8 @@ void QWidgetTextControl::insertFromMimeData(const QMimeData *source) bool hasData = false; QTextDocumentFragment fragment; #if QT_CONFIG(textmarkdownreader) - if (source->formats().first() == "text/markdown"_L1) { + const auto formats = source->formats(); + if (formats.size() && formats.first() == "text/markdown"_L1) { auto s = QString::fromUtf8(source->data("text/markdown"_L1)); fragment = QTextDocumentFragment::fromMarkdown(s); hasData = true; @@ -3477,7 +3489,7 @@ void QTextEditMimeData::setup() const that->setData("application/vnd.oasis.opendocument.text"_L1, buffer.data()); } #endif - that->setText(fragment.toRawText()); + that->setText(fragment.toPlainText()); fragment = QTextDocumentFragment(); } |