4

I didn't manage to select the first item of the completer when the popup is displayed in PopupCompletion mode. My current code that doesnt work:

completer->setCompletionPrefix(text);
QItemSelectionModel* sm = new QItemSelectionModel(completer->completionModel());
sm->select(completer->completionModel()->index(0,0), QItemSelectionModel::Select);
completer->popup()->setSelectionModel(sm);

Any suggestions?

Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
Antoine
  • 910
  • 1
  • 9
  • 26

2 Answers2

2

I would try changing the order of the last 2 lines:

completer->popup()->setSelectionModel(sm);
sm->select(completer->completionModel()->index(0,0), QItemSelectionModel::Select);

Probably the change of the selection for the popup (its a view) ocurs when selectionChanged() is emited. So you have to set first the selection model, then do the select.

void QItemSelectionModel::select ( const QModelIndex & index, QItemSelectionModel::SelectionFlags command ) [virtual slot]

Selects the model item index using the specified command, and emits selectionChanged().

BTW, u dont have to create a new selection model, just ask the popup for it (Againt, its a view):

completer->popup()->selectionModel();

http://qt-project.org/doc/qt-5.0/qtwidgets/qabstractitemview.html#selectionModel

trompa
  • 1,967
  • 1
  • 18
  • 26
0

I don't know if this is what you wanted, but in my case I wanted to be able to press enter and auto-select the first item in the pop-up list (as it does with UnfilteredPopupCompletion). What worked for me was:

class AutoSelectFirstFilter : public QObject
{
    Q_OBJECT

protected:
    virtual bool eventFilter(QObject *obj, QEvent *event) override
    {
        if (event->type() == QEvent::KeyPress)
        {
            if(static_cast<QKeyEvent *>(event)->key() == Qt::Key_Return)
            {
                QAbstractItemView* l = static_cast<QAbstractItemView*>(obj);
                QModelIndex i = l->model()->index(0,0);
                if(i.isValid())
                    l->selectionModel()->select(i, QItemSelectionModel::Select);
            }
        }
        return false;
    }
};

and than:

AutoSelectFirstFilter tmp;
completer->popup()->installEventFilter(&tmp);

PS: Don't forget to re-run qmake.

Adriel Jr
  • 2,451
  • 19
  • 25
  • This worked for me, but rather than "selecting" when the users presses `Qt::Key_Return` (which doesn't capture presses to `Qt::Key_Enter`) I'd recommend changing the "current" index instead (which is like highlighting the top choice). Don't cast `QKeyEvent` nor compare with any specific keys, just use: `l->selectionModel()->setCurrentIndex(i, QItemSelectionModel::Current);` – MasterHD Aug 13 '22 at 16:32