diff --git a/src/kiwixchoicebox.cpp b/src/kiwixchoicebox.cpp index fb296ce..c36d44e 100644 --- a/src/kiwixchoicebox.cpp +++ b/src/kiwixchoicebox.cpp @@ -48,9 +48,9 @@ KiwixChoiceBox::KiwixChoiceBox(QWidget *parent) : connect(choiceSelector, &QListWidget::itemPressed, this, [=](QListWidgetItem *item) { searcher->clear(); if (item->isSelected()) { - addSelection(item->text(), item->data(Qt::UserRole).toString()); + addSelection(item); } else { - removeSelection(item->text()); + removeSelection(item); } }); @@ -155,24 +155,38 @@ void KiwixChoiceBox::keyPressEvent(QKeyEvent *event) } } -bool KiwixChoiceBox::addSelection(QString key, QString value) +bool KiwixChoiceBox::addSelection(QListWidgetItem *item) { + auto key = item->text(); + auto value = item->data(Qt::UserRole).toString(); auto chItem = new ChoiceItem(key, value); connect(chItem, &ChoiceItem::closeButtonClicked, [=](QString text) { - removeSelection(text); + auto selectionItems = choiceSelector->findItems(text, Qt::MatchExactly); + if (selectionItems.size() != 1) return; + removeSelection(selectionItems[0]); }); chItem->setObjectName(key); currentChoicesLayout->insertWidget(ui->currentChoices->children().count() - 2, chItem); searcher->setFixedWidth(20); + // put on top of list + item = choiceSelector->takeItem(choiceSelector->row(item)); + choiceSelector->insertItem(0, item); + item->setSelected(true); + searcher->setFocus(); emit(choiceUpdated(getCurrentSelected())); return true; } -bool KiwixChoiceBox::removeSelection(QString selection) +bool KiwixChoiceBox::removeSelection(QListWidgetItem *item) { - auto chItem = ui->currentChoices->findChild(selection); + auto chItem = ui->currentChoices->findChild(item->text()); chItem->deleteLater(); + // selected items are always shown at top, put it after the last selected item + item->setSelected(false); + auto selItems = choiceSelector->selectedItems(); + item = choiceSelector->takeItem(choiceSelector->row(item)); + choiceSelector->insertItem(selItems.size(), item); emit(choiceUpdated(getCurrentSelected())); return true; } @@ -212,8 +226,7 @@ void KiwixChoiceBox::setSelections(SelectionList selections, QStringList default item->setData(Qt::UserRole, selection.first); choiceSelector->addItem(item); if (defaultSelection.contains(selection.first)) { - item->setSelected(true); - addSelection(item->text(), item->data(Qt::UserRole).toString()); + addSelection(item); } } if (choiceSelector->selectedItems().isEmpty()) diff --git a/src/kiwixchoicebox.h b/src/kiwixchoicebox.h index 053f0a5..eb7aa88 100644 --- a/src/kiwixchoicebox.h +++ b/src/kiwixchoicebox.h @@ -50,9 +50,9 @@ private: FlowLayout *currentChoicesLayout; KiwixLineEdit *searcher; QStringList getCurrentSelected(); - bool removeSelection(QString selection); + bool removeSelection(QListWidgetItem *item); void clearSelections(); - bool addSelection(QString key, QString value); + bool addSelection(QListWidgetItem *item); void showOptions(); void hideOptions(); QString m_type;