Fix selection after inserting items in wxListBox in wxOSX

We need to adjust the indices of the currently selected items as we need
to keep the same items, not the same indices, selected after new items
insertion.

Closes #18902.
This commit is contained in:
Andreas Falkenhahn
2020-12-05 22:45:13 +01:00
committed by Vadim Zeitlin
parent f7d50ed18c
commit 8bf53a7782
2 changed files with 51 additions and 3 deletions

View File

@@ -170,6 +170,8 @@ protected:
wxArrayPtrVoid m_itemsClientData; wxArrayPtrVoid m_itemsClientData;
private: private:
// Mostly the same as DoSetSelection() but doesn't call EnsureVisible().
void DoSetSelectionWithoutEnsureVisible(int n, bool select);
wxDECLARE_DYNAMIC_CLASS(wxListBox); wxDECLARE_DYNAMIC_CLASS(wxListBox);
wxDECLARE_EVENT_TABLE(); wxDECLARE_EVENT_TABLE();

View File

@@ -191,6 +191,14 @@ void wxListBox::DoSetSelection(int n, bool select)
wxCHECK_RET( n == wxNOT_FOUND || IsValid(n), wxCHECK_RET( n == wxNOT_FOUND || IsValid(n),
wxT("invalid index in wxListBox::SetSelection") ); wxT("invalid index in wxListBox::SetSelection") );
DoSetSelectionWithoutEnsureVisible(n, select);
if (select)
EnsureVisible(n);
}
void wxListBox::DoSetSelectionWithoutEnsureVisible(int n, bool select)
{
m_blockEvents = true; m_blockEvents = true;
if ( n == wxNOT_FOUND ) if ( n == wxNOT_FOUND )
@@ -201,9 +209,6 @@ void wxListBox::DoSetSelection(int n, bool select)
m_blockEvents = false; m_blockEvents = false;
UpdateOldSelections(); UpdateOldSelections();
if (select)
EnsureVisible(n);
} }
bool wxListBox::IsSelected(int n) const bool wxListBox::IsSelected(int n) const
@@ -349,6 +354,23 @@ int wxListBox::DoInsertItems(const wxArrayStringsAdapter& items,
{ {
int idx = wxNOT_FOUND; int idx = wxNOT_FOUND;
unsigned int startpos = pos; unsigned int startpos = pos;
wxArrayInt selections;
if ( !IsSorted() )
{
if ( HasMultipleSelection() )
{
GetSelections(selections);
}
else
{
int sel = GetSelection();
if ( sel != wxNOT_FOUND )
{
selections.Add(sel);
}
}
}
const unsigned int numItems = items.GetCount(); const unsigned int numItems = items.GetCount();
for ( unsigned int i = 0; i < numItems; ++i ) for ( unsigned int i = 0; i < numItems; ++i )
@@ -367,6 +389,30 @@ int wxListBox::DoInsertItems(const wxArrayStringsAdapter& items,
GetListPeer()->UpdateLineToEnd(startpos); GetListPeer()->UpdateLineToEnd(startpos);
const size_t numSelections = selections.size();
for ( size_t i = 0; i < numSelections; ++i )
{
if ( startpos <= selections[i] )
{
if ( HasMultipleSelection() )
{
size_t j;
// Do not deselect item if it is to be selected below
for ( j = 0; j < numSelections; ++j )
{
if ( selections[i] == selections[j] + numItems )
break;
}
if ( j == numSelections )
Deselect(selections[i]);
}
DoSetSelectionWithoutEnsureVisible(selections[i] + numItems, true);
}
}
InvalidateBestSize(); InvalidateBestSize();
UpdateOldSelections(); UpdateOldSelections();