summaryrefslogtreecommitdiffstats
path: root/src/widgets/widgets/qcombobox.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/widgets/widgets/qcombobox.cpp')
-rw-r--r--src/widgets/widgets/qcombobox.cpp567
1 files changed, 330 insertions, 237 deletions
diff --git a/src/widgets/widgets/qcombobox.cpp b/src/widgets/widgets/qcombobox.cpp
index 9caac239f9..06de5566ff 100644
--- a/src/widgets/widgets/qcombobox.cpp
+++ b/src/widgets/widgets/qcombobox.cpp
@@ -12,7 +12,7 @@
#if QT_CONFIG(tableview)
#include <qtableview.h>
#endif
-#include <qitemdelegate.h>
+#include <qabstractitemdelegate.h>
#include <qmap.h>
#if QT_CONFIG(menu)
#include <qmenu.h>
@@ -48,6 +48,9 @@
#if QT_CONFIG(accessibility)
#include "qaccessible.h"
#endif
+#include <array>
+
+#include <QtCore/qpointer.h>
QT_BEGIN_NAMESPACE
@@ -58,12 +61,14 @@ QComboBoxPrivate::QComboBoxPrivate()
shownOnce(false),
duplicatesEnabled(false),
frame(true),
- inserting(false)
+ inserting(false),
+ hidingPopup(false)
{
}
QComboBoxPrivate::~QComboBoxPrivate()
{
+ disconnectModel();
#ifdef Q_OS_MAC
cleanupNativePopup();
#endif
@@ -199,7 +204,7 @@ bool QComboMenuDelegate::editorEvent(QEvent *event, QAbstractItemModel *model,
}
#if QT_CONFIG(completer)
-void QComboBoxPrivate::_q_completerActivated(const QModelIndex &index)
+void QComboBoxPrivate::completerActivated(const QModelIndex &index)
{
Q_Q(QComboBox);
#if QT_CONFIG(proxymodel)
@@ -225,15 +230,6 @@ void QComboBoxPrivate::_q_completerActivated(const QModelIndex &index)
}
}
#endif
-
-# ifdef QT_KEYPAD_NAVIGATION
- if ( QApplicationPrivate::keypadNavigationEnabled()
- && q->isEditable()
- && q->completer()
- && q->completer()->completionMode() == QCompleter::UnfilteredPopupCompletion ) {
- q->setEditFocus(false);
- }
-# endif // QT_KEYPAD_NAVIGATION
}
#endif // QT_CONFIG(completer)
@@ -248,7 +244,7 @@ void QComboBoxPrivate::updateArrow(QStyle::StateFlag state)
q->update(q->rect());
}
-void QComboBoxPrivate::_q_modelReset()
+void QComboBoxPrivate::modelReset()
{
Q_Q(QComboBox);
if (lineEdit) {
@@ -260,7 +256,7 @@ void QComboBoxPrivate::_q_modelReset()
q->update();
}
-void QComboBoxPrivate::_q_modelDestroyed()
+void QComboBoxPrivate::modelDestroyed()
{
model = QAbstractItemModelPrivate::staticEmptyModel();
}
@@ -498,11 +494,13 @@ QComboBoxPrivateContainer::QComboBoxPrivateContainer(QAbstractItemView *itemView
if (top) {
layout->insertWidget(0, top);
- connect(top, SIGNAL(doScroll(int)), this, SLOT(scrollItemView(int)));
+ connect(top, &QComboBoxPrivateScroller::doScroll,
+ this, &QComboBoxPrivateContainer::scrollItemView);
}
if (bottom) {
layout->addWidget(bottom);
- connect(bottom, SIGNAL(doScroll(int)), this, SLOT(scrollItemView(int)));
+ connect(bottom, &QComboBoxPrivateScroller::doScroll,
+ this, &QComboBoxPrivateContainer::scrollItemView);
}
// Some styles (Mac) have a margin at the top and bottom of the popup.
@@ -511,6 +509,12 @@ QComboBoxPrivateContainer::QComboBoxPrivateContainer(QAbstractItemView *itemView
updateStyleSettings();
}
+QComboBoxPrivateContainer::~QComboBoxPrivateContainer()
+{
+ disconnect(view, &QAbstractItemView::destroyed,
+ this, &QComboBoxPrivateContainer::viewDestroyed);
+}
+
void QComboBoxPrivateContainer::scrollItemView(int action)
{
#if QT_CONFIG(scrollbar)
@@ -591,13 +595,13 @@ void QComboBoxPrivateContainer::setItemView(QAbstractItemView *itemView)
view->removeEventFilter(this);
view->viewport()->removeEventFilter(this);
#if QT_CONFIG(scrollbar)
- disconnect(view->verticalScrollBar(), SIGNAL(valueChanged(int)),
- this, SLOT(updateScrollers()));
- disconnect(view->verticalScrollBar(), SIGNAL(rangeChanged(int,int)),
- this, SLOT(updateScrollers()));
+ disconnect(view->verticalScrollBar(), &QScrollBar::valueChanged,
+ this, &QComboBoxPrivateContainer::updateScrollers);
+ disconnect(view->verticalScrollBar(), &QScrollBar::rangeChanged,
+ this, &QComboBoxPrivateContainer::updateScrollers);
#endif
- disconnect(view, SIGNAL(destroyed()),
- this, SLOT(viewDestroyed()));
+ disconnect(view, &QAbstractItemView::destroyed,
+ this, &QComboBoxPrivateContainer::viewDestroyed);
if (isAncestorOf(view))
delete view;
@@ -628,13 +632,13 @@ void QComboBoxPrivateContainer::setItemView(QAbstractItemView *itemView)
view->setLineWidth(0);
view->setEditTriggers(QAbstractItemView::NoEditTriggers);
#if QT_CONFIG(scrollbar)
- connect(view->verticalScrollBar(), SIGNAL(valueChanged(int)),
- this, SLOT(updateScrollers()));
- connect(view->verticalScrollBar(), SIGNAL(rangeChanged(int,int)),
- this, SLOT(updateScrollers()));
+ connect(view->verticalScrollBar(), &QScrollBar::valueChanged,
+ this, &QComboBoxPrivateContainer::updateScrollers);
+ connect(view->verticalScrollBar(), &QScrollBar::rangeChanged,
+ this, &QComboBoxPrivateContainer::updateScrollers);
#endif
- connect(view, SIGNAL(destroyed()),
- this, SLOT(viewDestroyed()));
+ connect(view, &QAbstractItemView::destroyed,
+ this, &QComboBoxPrivateContainer::viewDestroyed);
}
/*!
@@ -723,6 +727,7 @@ bool QComboBoxPrivateContainer::eventFilter(QObject *o, QEvent *e)
#endif
if (view->currentIndex().isValid() && view->currentIndex().flags().testFlag(Qt::ItemIsEnabled)) {
combo->hidePopup();
+ keyEvent->accept();
emit itemSelected(view->currentIndex());
}
return true;
@@ -732,11 +737,13 @@ bool QComboBoxPrivateContainer::eventFilter(QObject *o, QEvent *e)
Q_FALLTHROUGH();
case Qt::Key_F4:
combo->hidePopup();
+ keyEvent->accept();
+ emit itemSelected(view->currentIndex());
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
@@ -912,8 +919,11 @@ QStyleOptionComboBox QComboBoxPrivateContainer::comboStyleOption() const
\fn void QComboBox::currentTextChanged(const QString &text)
\since 5.0
- This signal is sent whenever currentText changes. The new value
- is passed as \a text.
+ This signal is emitted whenever currentText changes.
+ The new value is passed as \a text.
+
+ \note It is not emitted, if currentText remains the same,
+ even if currentIndex changes.
*/
/*!
@@ -939,39 +949,34 @@ QComboBox::QComboBox(QComboBoxPrivate &dd, QWidget *parent)
/*!
\class QComboBox
- \brief The QComboBox widget is a combined button and popup list.
+ \brief The QComboBox widget combines a button with a dropdown list.
\ingroup basicwidgets
\inmodule QtWidgets
- \image windows-combobox.png
-
- A QComboBox provides a means of presenting a list of options to the user
- in a way that takes up the minimum amount of screen space.
-
- A combobox is a selection widget that displays the current item,
- and can pop up a list of selectable items. A combobox may be editable,
- allowing the user to modify each item in the list.
-
- Comboboxes can contain pixmaps as well as strings; the
- insertItem() and setItemText() functions are suitably overloaded.
- For editable comboboxes, the function clearEditText() is provided,
+ \table
+ \row
+ \li \inlineimage collapsed_combobox.png
+ \caption Collapsed QCombobox
+ \li
+ \inlineimage expanded_combobox.png
+ \caption Expanded QCombobox
+ \endtable
+
+ \section1 Display Features
+ A QComboBox is a compact way to present a list of options to the user.
+
+ A combobox is a selection widget that shows the current item,
+ and pops up a list of selectable items when clicked. Comboboxes can
+ contain pixmaps as well as strings if the insertItem() and setItemText()
+ functions are suitably overloaded.
+
+ \section1 Editing Features
+ A combobox may be editable, allowing the user to modify each item in the
+ list. For editable comboboxes, the function clearEditText() is provided,
to clear the displayed string without changing the combobox's
contents.
- There are three signals emitted if the current item of a combobox
- changes, currentIndexChanged(), currentTextChanged() and activated().
- currentIndexChanged() and currentTextChanged() are always emitted
- regardless if the change
- was done programmatically or by user interaction, while
- activated() is only emitted when the change is caused by user
- interaction. The highlighted() signal is emitted when the user
- highlights an item in the combobox popup list. All three signals
- exist in two versions, one with a QString argument and one with an
- \c int argument. If the user selects or highlights a pixmap, only
- the \c int signals are emitted. Whenever the text of an editable
- combobox is changed the editTextChanged() signal is emitted.
-
When the user enters a new string in an editable combobox, the
widget may or may not insert it, and it can insert it in several
locations. The default policy is \l InsertAtBottom but you can change
@@ -994,17 +999,33 @@ QComboBox::QComboBox(QComboBoxPrivate &dd, QWidget *parent)
setCompleter() and whether or not the user can add duplicates
is set with setDuplicatesEnabled().
- QComboBox uses the \l{Model/View Programming}{model/view
- framework} for its popup list and to store its items. By default
- a QStandardItemModel stores the items and a QListView subclass
- displays the popuplist. You can access the model and view directly
- (with model() and view()), but QComboBox also provides functions
- to set and get item data (e.g., setItemData() and itemText()). You
- can also set a new model and view (with setModel() and setView()).
- For the text and icon in the combobox label, the data in the model
- that has the Qt::DisplayRole and Qt::DecorationRole is used. Note
- that you cannot alter the \l{QAbstractItemView::}{SelectionMode}
- of the view(), e.g., by using
+ \section1 Signals
+ There are three signals emitted if the current item of a combobox
+ changes: currentIndexChanged(), currentTextChanged(), and activated().
+ currentIndexChanged() and currentTextChanged() are always emitted
+ regardless if the change
+ was done programmatically or by user interaction, while
+ activated() is only emitted when the change is caused by user
+ interaction. The highlighted() signal is emitted when the user
+ highlights an item in the combobox popup list. All three signals
+ exist in two versions, one with a QString argument and one with an
+ \c int argument. If the user selects or highlights a pixmap, only
+ the \c int signals are emitted. Whenever the text of an editable
+ combobox is changed, the editTextChanged() signal is emitted.
+
+ \section1 Model/View Framework
+
+ QComboBox uses the \l{Model/View Programming}{model/view framework} for its
+ popup list and to store its items. By default a QStandardItemModel stores
+ the items and a QListView subclass displays the popuplist. You can access
+ the model and view directly (with model() and view()), but QComboBox also
+ provides functions to set and get item data, for example, setItemData() and
+ itemText(). You can also set a new model and view (with setModel()
+ and setView()). For the text and icon in the combobox label, the data in
+ the model that has the Qt::DisplayRole and Qt::DecorationRole is used.
+
+ \note You cannot alter the \l{QAbstractItemView::}{SelectionMode}
+ of the view(), for example, by using
\l{QAbstractItemView::}{setSelectionMode()}.
\sa QLineEdit, QSpinBox, QRadioButton, QButtonGroup
@@ -1041,27 +1062,30 @@ QComboBoxPrivateContainer* QComboBoxPrivate::viewContainer()
Q_Q(QComboBox);
container = new QComboBoxPrivateContainer(new QComboBoxListView(q), q);
+ disconnectModel();
container->itemView()->setModel(model);
+ connectModel();
container->itemView()->setTextElideMode(Qt::ElideMiddle);
updateDelegate(true);
updateLayoutDirection();
updateViewContainerPaletteAndOpacity();
- QObject::connect(container, SIGNAL(itemSelected(QModelIndex)),
- q, SLOT(_q_itemSelected(QModelIndex)));
- QObject::connect(container->itemView()->selectionModel(),
- SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- q, SLOT(_q_emitHighlighted(QModelIndex)));
- QObject::connect(container, SIGNAL(resetButton()), q, SLOT(_q_resetButton()));
+ QObjectPrivate::connect(container, &QComboBoxPrivateContainer::itemSelected,
+ this, &QComboBoxPrivate::itemSelected);
+ QObjectPrivate::connect(container->itemView()->selectionModel(),
+ &QItemSelectionModel::currentChanged,
+ this, &QComboBoxPrivate::emitHighlighted);
+ QObjectPrivate::connect(container, &QComboBoxPrivateContainer::resetButton,
+ this, &QComboBoxPrivate::resetButton);
return container;
}
-void QComboBoxPrivate::_q_resetButton()
+void QComboBoxPrivate::resetButton()
{
updateArrow(QStyle::State_None);
}
-void QComboBoxPrivate::_q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
+void QComboBoxPrivate::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
Q_Q(QComboBox);
if (inserting || topLeft.parent() != root)
@@ -1079,7 +1103,7 @@ void QComboBoxPrivate::_q_dataChanged(const QModelIndex &topLeft, const QModelIn
lineEdit->setText(text);
updateLineEditGeometry();
} else {
- emit q->currentTextChanged(text);
+ updateCurrentText(text);
}
q->update();
#if QT_CONFIG(accessibility)
@@ -1089,7 +1113,7 @@ void QComboBoxPrivate::_q_dataChanged(const QModelIndex &topLeft, const QModelIn
}
}
-void QComboBoxPrivate::_q_rowsInserted(const QModelIndex &parent, int start, int end)
+void QComboBoxPrivate::rowsInserted(const QModelIndex &parent, int start, int end)
{
Q_Q(QComboBox);
if (inserting || parent != root)
@@ -1104,20 +1128,31 @@ void QComboBoxPrivate::_q_rowsInserted(const QModelIndex &parent, int start, int
// set current index if combo was previously empty and there is no placeholderText
if (start == 0 && (end - start + 1) == q->count() && !currentIndex.isValid() &&
placeholderText.isEmpty()) {
+#if QT_CONFIG(accessibility)
+ // This might have been called by the model emitting rowInserted(), at which
+ // point the view won't have updated the accessibility bridge yet about its new
+ // dimensions. Do it now so that the change of the selection matches the row
+ // indexes of the accessibility bridge's representation.
+ if (container && container->itemView()) {
+ QAccessibleTableModelChangeEvent event(container->itemView(),
+ QAccessibleTableModelChangeEvent::ModelReset);
+ QAccessible::updateAccessibility(&event);
+ }
+#endif
q->setCurrentIndex(0);
// need to emit changed if model updated index "silently"
} else if (currentIndex.row() != indexBeforeChange) {
q->update();
- _q_emitCurrentIndexChanged(currentIndex);
+ emitCurrentIndexChanged(currentIndex);
}
}
-void QComboBoxPrivate::_q_updateIndexBeforeChange()
+void QComboBoxPrivate::updateIndexBeforeChange()
{
indexBeforeChange = currentIndex.row();
}
-void QComboBoxPrivate::_q_rowsRemoved(const QModelIndex &parent, int /*start*/, int /*end*/)
+void QComboBoxPrivate::rowsRemoved(const QModelIndex &parent, int /*start*/, int /*end*/)
{
Q_Q(QComboBox);
if (parent != root)
@@ -1129,6 +1164,12 @@ void QComboBoxPrivate::_q_rowsRemoved(const QModelIndex &parent, int /*start*/,
q->updateGeometry();
}
+ // model has removed the last row
+ if (model->rowCount(root) == 0) {
+ setCurrentIndex(QModelIndex());
+ return;
+ }
+
// model has changed the currentIndex
if (currentIndex.row() != indexBeforeChange) {
if (!currentIndex.isValid() && q->count()) {
@@ -1140,7 +1181,7 @@ void QComboBoxPrivate::_q_rowsRemoved(const QModelIndex &parent, int /*start*/,
updateLineEditGeometry();
}
q->update();
- _q_emitCurrentIndexChanged(currentIndex);
+ emitCurrentIndexChanged(currentIndex);
}
}
@@ -1249,7 +1290,7 @@ Qt::MatchFlags QComboBoxPrivate::matchFlags() const
}
-void QComboBoxPrivate::_q_editingFinished()
+void QComboBoxPrivate::editingFinished()
{
Q_Q(QComboBox);
if (!lineEdit)
@@ -1281,13 +1322,13 @@ void QComboBoxPrivate::_q_editingFinished()
}
-void QComboBoxPrivate::_q_returnPressed()
+void QComboBoxPrivate::returnPressed()
{
Q_Q(QComboBox);
// The insertion code below does not apply when the policy is QComboBox::NoInsert.
// In case a completer is installed, item activation via the completer is handled
- // in _q_completerActivated(). Otherwise _q_editingFinished() updates the current
+ // in completerActivated(). Otherwise editingFinished() updates the current
// index as appropriate.
if (insertPolicy == QComboBox::NoInsert)
return;
@@ -1345,7 +1386,7 @@ void QComboBoxPrivate::_q_returnPressed()
}
}
-void QComboBoxPrivate::_q_itemSelected(const QModelIndex &item)
+void QComboBoxPrivate::itemSelected(const QModelIndex &item)
{
Q_Q(QComboBox);
if (item != currentIndex) {
@@ -1367,7 +1408,7 @@ void QComboBoxPrivate::emitActivated(const QModelIndex &index)
emit q->textActivated(text);
}
-void QComboBoxPrivate::_q_emitHighlighted(const QModelIndex &index)
+void QComboBoxPrivate::emitHighlighted(const QModelIndex &index)
{
Q_Q(QComboBox);
if (!index.isValid())
@@ -1377,14 +1418,14 @@ void QComboBoxPrivate::_q_emitHighlighted(const QModelIndex &index)
emit q->textHighlighted(text);
}
-void QComboBoxPrivate::_q_emitCurrentIndexChanged(const QModelIndex &index)
+void QComboBoxPrivate::emitCurrentIndexChanged(const QModelIndex &index)
{
Q_Q(QComboBox);
const QString text = itemText(index);
emit q->currentIndexChanged(index.row());
// signal lineEdit.textChanged already connected to signal currentTextChanged, so don't emit double here
if (!lineEdit)
- emit q->currentTextChanged(text);
+ updateCurrentText(text);
#if QT_CONFIG(accessibility)
QAccessibleValueChangeEvent event(q, text);
QAccessible::updateAccessibility(&event);
@@ -1410,11 +1451,13 @@ QComboBox::~QComboBox()
Q_D(QComboBox);
QT_TRY {
- disconnect(d->model, SIGNAL(destroyed()),
- this, SLOT(_q_modelDestroyed()));
+ d->disconnectModel();
} QT_CATCH(...) {
; // objects can't throw in destructor
}
+
+ // Dispose of container before QComboBox goes away
+ delete d->container;
}
/*!
@@ -1445,7 +1488,7 @@ void QComboBox::setMaxVisibleItems(int maxItems)
/*!
\property QComboBox::count
- \brief the number of items in the combobox
+ \brief the number of items in the combobox.
By default, for an empty combo box, this property has a value of 0.
*/
@@ -1457,7 +1500,7 @@ int QComboBox::count() const
/*!
\property QComboBox::maxCount
- \brief the maximum number of items allowed in the combobox
+ \brief the maximum number of items allowed in the combobox.
\note If you set the maximum number to be less then the current
amount of items in the combobox, the extra items will be
@@ -1490,7 +1533,7 @@ int QComboBox::maxCount() const
/*!
\property QComboBox::duplicatesEnabled
- \brief whether the user can enter duplicate items into the combobox
+ \brief whether the user can enter duplicate items into the combobox.
Note that it is always possible to programmatically insert duplicate items into the
combobox.
@@ -1536,7 +1579,7 @@ int QComboBox::findData(const QVariant &data, int role, Qt::MatchFlags flags) co
/*!
\property QComboBox::insertPolicy
\brief the policy used to determine where user-inserted items should
- appear in the combobox
+ appear in the combobox.
The default value is \l InsertAtBottom, indicating that new items will appear
at the bottom of the list of items.
@@ -1559,7 +1602,7 @@ void QComboBox::setInsertPolicy(InsertPolicy policy)
/*!
\property QComboBox::sizeAdjustPolicy
\brief the policy describing how the size of the combobox changes
- when the content changes
+ when the content changes.
The default value is \l AdjustToContentsOnFirstShow.
@@ -1650,7 +1693,7 @@ void QComboBox::setIconSize(const QSize &size)
/*!
\property QComboBox::placeholderText
- \brief Sets a \a placeholderText text shown when no valid index is set
+ \brief Sets a \a placeholderText text shown when no valid index is set.
The \a placeholderText will be shown when an invalid index is set. The
text is not accessible in the dropdown list. When this function is called
@@ -1689,7 +1732,7 @@ QString QComboBox::placeholderText() const
/*!
\property QComboBox::editable
- \brief whether the combo box can be edited by the user
+ \brief whether the combo box can be edited by the user.
By default, this property is \c false. The effect of editing depends
on the insert policy.
@@ -1728,6 +1771,8 @@ void QComboBoxPrivate::updateDelegate(bool force)
QIcon QComboBoxPrivate::itemIcon(const QModelIndex &index) const
{
+ if (!index.isValid())
+ return {};
QVariant decoration = model->data(index, Qt::DecorationRole);
if (decoration.userType() == QMetaType::QPixmap)
return QIcon(qvariant_cast<QPixmap>(decoration));
@@ -1798,13 +1843,18 @@ void QComboBox::setLineEdit(QLineEdit *edit)
#endif
if (d->lineEdit->parent() != this)
d->lineEdit->setParent(this);
- connect(d->lineEdit, SIGNAL(returnPressed()), this, SLOT(_q_returnPressed()));
- connect(d->lineEdit, SIGNAL(editingFinished()), this, SLOT(_q_editingFinished()));
- connect(d->lineEdit, SIGNAL(textChanged(QString)), this, SIGNAL(editTextChanged(QString)));
- connect(d->lineEdit, SIGNAL(textChanged(QString)), this, SIGNAL(currentTextChanged(QString)));
- connect(d->lineEdit, SIGNAL(cursorPositionChanged(int,int)), this, SLOT(updateMicroFocus()));
- connect(d->lineEdit, SIGNAL(selectionChanged()), this, SLOT(updateMicroFocus()));
- connect(d->lineEdit->d_func()->control, SIGNAL(updateMicroFocus()), this, SLOT(updateMicroFocus()));
+ QObjectPrivate::connect(d->lineEdit, &QLineEdit::returnPressed,
+ d, &QComboBoxPrivate::returnPressed);
+ QObjectPrivate::connect(d->lineEdit, &QLineEdit::editingFinished,
+ d, &QComboBoxPrivate::editingFinished);
+ connect(d->lineEdit, &QLineEdit::textChanged, this, &QComboBox::editTextChanged);
+ connect(d->lineEdit, &QLineEdit::textChanged, this, &QComboBox::currentTextChanged);
+ QObjectPrivate::connect(d->lineEdit, &QLineEdit::cursorPositionChanged,
+ d, &QComboBoxPrivate::updateMicroFocus);
+ QObjectPrivate::connect(d->lineEdit, &QLineEdit::selectionChanged,
+ d, &QComboBoxPrivate::updateMicroFocus);
+ QObjectPrivate::connect(d->lineEdit->d_func()->control, &QWidgetLineControl::updateMicroFocus,
+ d, &QComboBoxPrivate::updateMicroFocus);
d->lineEdit->setFrame(false);
d->lineEdit->setContextMenuPolicy(Qt::NoContextMenu);
d->updateFocusPolicy();
@@ -1906,7 +1956,8 @@ void QComboBox::setCompleter(QCompleter *c)
}
d->lineEdit->setCompleter(c);
if (c) {
- connect(c, SIGNAL(activated(QModelIndex)), this, SLOT(_q_completerActivated(QModelIndex)));
+ QObjectPrivate::connect(c, QOverload<const QModelIndex &>::of(&QCompleter::activated),
+ d, &QComboBoxPrivate::completerActivated);
c->setWidget(this);
}
}
@@ -2000,59 +2051,60 @@ void QComboBox::setModel(QAbstractItemModel *model)
if (d->lineEdit && d->lineEdit->completer())
d->lineEdit->completer()->setModel(model);
#endif
- if (d->model) {
- disconnect(d->model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- disconnect(d->model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
- this, SLOT(_q_updateIndexBeforeChange()));
- disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_updateIndexBeforeChange()));
- disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
- disconnect(d->model, SIGNAL(destroyed()),
- this, SLOT(_q_modelDestroyed()));
- disconnect(d->model, SIGNAL(modelAboutToBeReset()),
- this, SLOT(_q_updateIndexBeforeChange()));
- disconnect(d->model, SIGNAL(modelReset()),
- this, SLOT(_q_modelReset()));
- if (d->model->QObject::parent() == this)
- delete d->model;
+ d->disconnectModel();
+ if (d->model && d->model->QObject::parent() == this) {
+ delete d->model;
+ d->model = nullptr;
}
d->model = model;
- connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_dataChanged(QModelIndex,QModelIndex)));
- connect(model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
- this, SLOT(_q_updateIndexBeforeChange()));
- connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(_q_rowsInserted(QModelIndex,int,int)));
- connect(model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
- this, SLOT(_q_updateIndexBeforeChange()));
- connect(model, SIGNAL(rowsRemoved(QModelIndex,int,int)),
- this, SLOT(_q_rowsRemoved(QModelIndex,int,int)));
- connect(model, SIGNAL(destroyed()),
- this, SLOT(_q_modelDestroyed()));
- connect(model, SIGNAL(modelAboutToBeReset()),
- this, SLOT(_q_updateIndexBeforeChange()));
- connect(model, SIGNAL(modelReset()),
- this, SLOT(_q_modelReset()));
-
if (d->container) {
d->container->itemView()->setModel(model);
- connect(d->container->itemView()->selectionModel(),
- SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- this, SLOT(_q_emitHighlighted(QModelIndex)), Qt::UniqueConnection);
+ QObjectPrivate::connect(d->container->itemView()->selectionModel(),
+ &QItemSelectionModel::currentChanged,
+ d, &QComboBoxPrivate::emitHighlighted, Qt::UniqueConnection);
}
+ d->connectModel();
+
setRootModelIndex(QModelIndex());
d->trySetValidIndex();
d->modelChanged();
}
+void QComboBoxPrivate::connectModel()
+{
+ if (!model)
+ return;
+
+ modelConnections = {
+ QObjectPrivate::connect(model, &QAbstractItemModel::dataChanged,
+ this, &QComboBoxPrivate::dataChanged),
+ QObjectPrivate::connect(model, &QAbstractItemModel::rowsAboutToBeInserted,
+ this, &QComboBoxPrivate::updateIndexBeforeChange),
+ QObjectPrivate::connect(model, &QAbstractItemModel::rowsInserted,
+ this, &QComboBoxPrivate::rowsInserted),
+ QObjectPrivate::connect(model, &QAbstractItemModel::rowsAboutToBeRemoved,
+ this, &QComboBoxPrivate::updateIndexBeforeChange),
+ QObjectPrivate::connect(model, &QAbstractItemModel::rowsRemoved,
+ this, &QComboBoxPrivate::rowsRemoved),
+ QObjectPrivate::connect(model, &QObject::destroyed,
+ this, &QComboBoxPrivate::modelDestroyed),
+ QObjectPrivate::connect(model, &QAbstractItemModel::modelAboutToBeReset,
+ this, &QComboBoxPrivate::updateIndexBeforeChange),
+ QObjectPrivate::connect(model, &QAbstractItemModel::modelReset,
+ this, &QComboBoxPrivate::modelReset)
+ };
+}
+
+void QComboBoxPrivate::disconnectModel()
+{
+ for (auto &connection : modelConnections)
+ QObject::disconnect(connection);
+}
+
/*!
Returns the root model item index for the items in the combobox.
@@ -2098,7 +2150,7 @@ int QComboBox::currentIndex() const
void QComboBox::setCurrentIndex(int index)
{
Q_D(QComboBox);
- QModelIndex mi = d->model->index(index, d->modelColumn, d->root);
+ QModelIndex mi = index >= 0 ? d->model->index(index, d->modelColumn, d->root) : QModelIndex();
d->setCurrentIndex(mi);
}
@@ -2135,13 +2187,24 @@ void QComboBoxPrivate::setCurrentIndex(const QModelIndex &mi)
}
updateLineEditGeometry();
}
- // If the model was reset to an empty, currentIndex will be invalidated
+ // If the model was reset to an empty one, currentIndex will be invalidated
// (because it's a QPersistentModelIndex), but the index change will never
- // be advertised. So we need an explicit check for such condition.
+ // be advertised. So an explicit check for this condition is needed.
+ // The variable used for that check has to be reset when a previously valid
+ // index becomes invalid.
const bool modelResetToEmpty = !normalized.isValid() && indexBeforeChange != -1;
+ if (modelResetToEmpty)
+ indexBeforeChange = -1;
+
if (indexChanged || modelResetToEmpty) {
+ QItemSelectionModel::SelectionFlags selectionMode = QItemSelectionModel::ClearAndSelect;
+ if (q->view()->selectionBehavior() == QAbstractItemView::SelectRows)
+ selectionMode.setFlag(QItemSelectionModel::Rows);
+ if (auto *model = q->view()->selectionModel())
+ model->setCurrentIndex(currentIndex, selectionMode);
+
q->update();
- _q_emitCurrentIndexChanged(currentIndex);
+ emitCurrentIndexChanged(currentIndex);
}
}
@@ -2270,7 +2333,7 @@ void QComboBox::insertItem(int index, const QIcon &icon, const QString &text, co
if (!values.isEmpty()) d->model->setItemData(item, values);
}
d->inserting = false;
- d->_q_rowsInserted(d->root, index, index);
+ d->rowsInserted(d->root, index, index);
++itemCount;
} else {
d->inserting = false;
@@ -2297,7 +2360,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
@@ -2318,7 +2381,7 @@ void QComboBox::insertItems(int index, const QStringList &list)
d->model->setData(item, list.at(i), Qt::EditRole);
}
d->inserting = false;
- d->_q_rowsInserted(d->root, index, index + insertCount - 1);
+ d->rowsInserted(d->root, index, index + insertCount - 1);
} else {
d->inserting = false;
}
@@ -2428,8 +2491,11 @@ void QComboBox::setView(QAbstractItemView *itemView)
return;
}
- if (itemView->model() != d->model)
+ if (itemView->model() != d->model) {
+ d->disconnectModel();
itemView->setModel(d->model);
+ d->connectModel();
+ }
d->viewContainer()->setItemView(itemView);
}
@@ -2461,12 +2527,13 @@ void QComboBoxPrivate::cleanupNativePopup()
if (!m_platformMenu)
return;
+ m_platformMenu->setVisible(false);
int count = int(m_platformMenu->tag());
for (int i = 0; i < count; ++i)
m_platformMenu->menuItemAt(i)->deleteLater();
delete m_platformMenu;
- m_platformMenu = 0;
+ m_platformMenu = nullptr;
}
/*!
@@ -2498,15 +2565,17 @@ bool QComboBoxPrivate::showNativePopup()
QVariant textVariant = model->data(rowIndex, Qt::EditRole);
item->setText(textVariant.toString());
QVariant iconVariant = model->data(rowIndex, Qt::DecorationRole);
+ const Qt::ItemFlags itemFlags = model->flags(rowIndex);
if (iconVariant.canConvert<QIcon>())
item->setIcon(iconVariant.value<QIcon>());
item->setCheckable(true);
item->setChecked(i == currentIndex);
+ item->setEnabled(itemFlags & Qt::ItemIsEnabled);
if (!currentItem || i == currentIndex)
currentItem = item;
IndexSetter setter = { i, q };
- QObject::connect(item, &QPlatformMenuItem::activated, setter);
+ QObject::connect(item, &QPlatformMenuItem::activated, q, setter);
m_platformMenu->insertMenuItem(item, 0);
m_platformMenu->syncMenuItem(item);
@@ -2521,15 +2590,18 @@ bool QComboBoxPrivate::showNativePopup()
else if (q->testAttribute(Qt::WA_MacMiniSize))
offset = QPoint(-2, 6);
+ [[maybe_unused]] QPointer<QComboBox> guard(q);
const QRect targetRect = QRect(tlw->mapFromGlobal(q->mapToGlobal(offset)), QSize());
m_platformMenu->showPopup(tlw, QHighDpi::toNativePixels(targetRect, tlw), currentItem);
#ifdef Q_OS_MACOS
- // The Cocoa popup will swallow any mouse release event.
- // We need to fake one here to un-press the button.
- QMouseEvent mouseReleased(QEvent::MouseButtonRelease, q->pos(), q->mapToGlobal(QPoint(0, 0)),
- Qt::LeftButton, Qt::MouseButtons(Qt::LeftButton), {});
- QCoreApplication::sendEvent(q, &mouseReleased);
+ if (guard) {
+ // The Cocoa popup will swallow any mouse release event.
+ // We need to fake one here to un-press the button.
+ QMouseEvent mouseReleased(QEvent::MouseButtonRelease, q->pos(), q->mapToGlobal(QPoint(0, 0)),
+ Qt::LeftButton, Qt::MouseButtons(Qt::LeftButton), {});
+ QCoreApplication::sendEvent(q, &mouseReleased);
+ }
#endif
return true;
@@ -2567,22 +2639,6 @@ void QComboBox::showPopup()
return;
#endif // Q_OS_MAC
-#ifdef QT_KEYPAD_NAVIGATION
-#if QT_CONFIG(completer)
- if (QApplicationPrivate::keypadNavigationEnabled() && d->completer) {
- // editable combo box is line edit plus completer
- setEditFocus(true);
- d->completer->complete(); // show popup
- return;
- }
-#endif
-#endif
-
- // set current item and select it
- QItemSelectionModel::SelectionFlags selectionMode = QItemSelectionModel::ClearAndSelect;
- if (view()->selectionBehavior() == QAbstractItemView::SelectRows)
- selectionMode.setFlag(QItemSelectionModel::Rows);
- view()->selectionModel()->setCurrentIndex(d->currentIndex, selectionMode);
QComboBoxPrivateContainer* container = d->viewContainer();
QRect listRect(style->subControlRect(QStyle::CC_ComboBox, &opt,
QStyle::SC_ComboBoxListBoxPopup, this));
@@ -2593,6 +2649,7 @@ void QComboBox::showPopup()
QPoint above = mapToGlobal(listRect.topLeft());
int aboveHeight = above.y() - screen.y();
bool boundToScreen = !window()->testAttribute(Qt::WA_DontShowOnScreen);
+ const auto listView = qobject_cast<QListView *>(d->viewContainer()->itemView());
{
int listHeight = 0;
@@ -2607,6 +2664,8 @@ void QComboBox::showPopup()
while (!toCheck.isEmpty()) {
QModelIndex parent = toCheck.pop();
for (int i = 0, end = d->model->rowCount(parent); i < end; ++i) {
+ if (listView && listView->isRowHidden(i))
+ continue;
QModelIndex idx = d->model->index(i, d->modelColumn, parent);
if (!idx.isValid())
continue;
@@ -2680,7 +2739,13 @@ void QComboBox::showPopup()
listRect.moveLeft(above.x());
// Position vertically so the currently selected item lines up
- // with the combo box.
+ // with the combo box. In order to do that, make sure that the item
+ // view is scrolled to the top first, otherwise calls to view()->visualRect()
+ // will return the geometry the selected item had the last time the popup
+ // was visible (and perhaps scrolled). And this will not match the geometry
+ // it will actually have when we resize the container to fit all the items
+ // further down in this function.
+ view()->scrollToTop();
const QRect currentItemRect = view()->visualRect(view()->currentIndex());
const int offset = listRect.top() - currentItemRect.top();
listRect.moveTop(above.y() + offset - listRect.top());
@@ -2782,10 +2847,6 @@ void QComboBox::showPopup()
#endif
container->update();
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplicationPrivate::keypadNavigationEnabled())
- view()->setEditFocus(true);
-#endif
if (startTimer) {
container->popupTimer.start();
container->maybeIgnoreMouseButtonRelease = true;
@@ -2805,60 +2866,64 @@ void QComboBox::showPopup()
void QComboBox::hidePopup()
{
Q_D(QComboBox);
- if (d->container && d->container->isVisible()) {
+ 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())
+ return;
+
#if QT_CONFIG(effects)
- QSignalBlocker modelBlocker(d->model);
- QSignalBlocker viewBlocker(d->container->itemView());
- QSignalBlocker containerBlocker(d->container);
- // Flash selected/triggered item (if any).
- if (style()->styleHint(QStyle::SH_Menu_FlashTriggeredItem)) {
- QItemSelectionModel *selectionModel = view() ? view()->selectionModel() : nullptr;
- if (selectionModel && selectionModel->hasSelection()) {
- QEventLoop eventLoop;
- const QItemSelection selection = selectionModel->selection();
-
- // Deselect item and wait 60 ms.
+ QItemSelectionModel *selectionModel = d->container->itemView()
+ ? d->container->itemView()->selectionModel() : nullptr;
+ // Flash selected/triggered item (if any) before hiding the popup.
+ if (style()->styleHint(QStyle::SH_Menu_FlashTriggeredItem) &&
+ selectionModel && selectionModel->hasSelection()) {
+ const QItemSelection selection = selectionModel->selection();
+
+ QTimer::singleShot(0, d->container, [d, selection, selectionModel]{
+ QSignalBlocker modelBlocker(d->model);
+ QSignalBlocker viewBlocker(d->container->itemView());
+ QSignalBlocker containerBlocker(d->container);
+
+ // Deselect item and wait 60 ms.
+ selectionModel->select(selection, QItemSelectionModel::Toggle);
+ QTimer::singleShot(60, d->container, [d, selection, selectionModel]{
+ QSignalBlocker modelBlocker(d->model);
+ QSignalBlocker viewBlocker(d->container->itemView());
+ QSignalBlocker containerBlocker(d->container);
selectionModel->select(selection, QItemSelectionModel::Toggle);
- QTimer::singleShot(60, &eventLoop, SLOT(quit()));
- eventLoop.exec();
+ QTimer::singleShot(20, d->container, [d] {
+ d->doHidePopup();
+ });
+ });
+ });
+ } else
+#endif // QT_CONFIG(effects)
+ {
+ d->doHidePopup();
+ }
+}
- // Select item and wait 20 ms.
- selectionModel->select(selection, QItemSelectionModel::Toggle);
- QTimer::singleShot(20, &eventLoop, SLOT(quit()));
- eventLoop.exec();
- }
- }
+void QComboBoxPrivate::doHidePopup()
+{
+ if (container && container->isVisible())
+ container->hide();
- // 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;
- }
+ resetButton();
+}
-#endif // Q_OS_MAC
- // Other platform implementations welcome :-)
- }
- containerBlocker.unblock();
- viewBlocker.unblock();
- modelBlocker.unblock();
+void QComboBoxPrivate::updateCurrentText(const QString &text)
+{
+ if (text == currentText)
+ return;
- if (!didFade)
-#endif // QT_CONFIG(effects)
- // Fade should implicitly hide as well ;-)
- d->container->hide();
- }
-#ifdef QT_KEYPAD_NAVIGATION
- if (QApplicationPrivate::keypadNavigationEnabled() && isEditable() && hasFocus())
- setEditFocus(true);
-#endif
- d->_q_resetButton();
+ currentText = text;
+ emit q_func()->currentTextChanged(text);
}
/*!
@@ -2938,9 +3003,26 @@ void QComboBox::changeEvent(QEvent *e)
Q_D(QComboBox);
switch (e->type()) {
case QEvent::StyleChange:
- if (d->container)
+ if (d->container) {
+// If on Windows, force recreation of ComboBox container, since
+// windows11 style depends on WA_TranslucentBackground
+#ifdef Q_OS_WIN
+ auto delegate = itemDelegate();
+ d->container->deleteLater();
+ // d->container needs to be set explicitly to nullptr
+ // since QComboBoxPrivate::viewContainer() only
+ // creates a new QComboBoxPrivateContainer when
+ // d->container has the value of nullptr
+ d->container = nullptr;
+ d->container = d->viewContainer();
+ delegate->setParent(d->container);
+ setItemDelegate(delegate);
+
+#endif
d->container->updateStyleSettings();
+ }
d->updateDelegate();
+
#ifdef Q_OS_MAC
case QEvent::MacSizeChange:
#endif
@@ -3064,9 +3146,7 @@ bool QComboBox::event(QEvent *event)
break;
#ifdef QT_KEYPAD_NAVIGATION
case QEvent::EnterEditFocus:
- if (!d->lineEdit)
- setEditFocus(false); // We never want edit focus if we are not editable
- else
+ if (d->lineEdit)
d->lineEdit->event(event); //so cursor starts
break;
case QEvent::LeaveEditFocus:
@@ -3113,7 +3193,10 @@ void QComboBoxPrivate::showPopupFromMouseEvent(QMouseEvent *e)
// viewContainer(), we avoid creating the QComboBoxPrivateContainer.
viewContainer()->initialClickPosition = q->mapToGlobal(e->position().toPoint());
}
+ QPointer<QComboBox> guard = q;
q->showPopup();
+ if (!guard)
+ return;
// The code below ensures that regular mousepress and pick item still works
// If it was not called the viewContainer would ignore event since it didn't have
// a mousePressEvent first.
@@ -3223,6 +3306,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,9 +3328,17 @@ void QComboBox::keyPressEvent(QKeyEvent *e)
break;
#endif
default:
+#if QT_CONFIG(shortcut)
+ if (d->container && d->container->isVisible() && e->matches(QKeySequence::Cancel)) {
+ hidePopup();
+ e->accept();
+ }
+#endif
+
if (!d->lineEdit) {
- if (!e->text().isEmpty())
- d->keyboardSearchString(e->text());
+ const auto text = e->text();
+ if (!text.isEmpty() && text.at(0).isPrint())
+ d->keyboardSearchString(text);
else
e->ignore();
}
@@ -3443,7 +3536,7 @@ QVariant QComboBox::inputMethodQuery(Qt::InputMethodQuery query, const QVariant
/*!
\property QComboBox::frame
- \brief whether the combo box draws itself with a frame
+ \brief whether the combo box draws itself with a frame.
If enabled (the default) the combo box draws itself inside a