Add wxWindow::CallForEachChild()

Adding such function was discussed a few times in the past and it's
going to be needed by wxWidgets itself in the next commit, so do add it,
finally, so that it could also be used from the application code too.
This commit is contained in:
Vadim Zeitlin 2023-02-21 16:55:17 +00:00
parent 18002cf6ca
commit 8687a0bad9
2 changed files with 37 additions and 0 deletions

View file

@ -784,6 +784,10 @@ public:
// needed just for extended runtime
const wxWindowList& GetWindowChildren() const { return GetChildren() ; }
// call the specified functor for all children, recursively
template <typename T>
void CallForEachChild(const T& fn);
// get the window before/after this one in the parents children list,
// returns nullptr if this is the first/last window
wxWindow *GetPrevSibling() const { return DoGetSibling(OrderBefore); }
@ -2057,6 +2061,15 @@ inline wxWindow *wxWindowBase::GetGrandParent() const
return m_parent ? m_parent->GetParent() : nullptr;
}
template <typename T>
void wxWindowBase::CallForEachChild(const T& fn)
{
fn(static_cast<wxWindow*>(this));
for ( auto& child : GetChildren() )
child->CallForEachChild(fn);
}
// ----------------------------------------------------------------------------
// global functions
// ----------------------------------------------------------------------------

View file

@ -592,6 +592,30 @@ public:
*/
virtual void AddChild(wxWindow* child);
/**
Invoke the given functor for all children of the given window
recursively.
This function calls @a functor for the window itself and then for all
of its children, recursively.
Example of using it for implementing a not very smart translation
function:
@code
void MyFrame::OnTranslate(wxCommandEvent&) {
CallForEachChild([](wxWindow* win) {
wxString rest;
if ( win->GetLabel().StartsWith("Hello ", &rest) )
win->SetLabel("Bonjour " + rest);
});
}
@endcode
@since 3.3.0
*/
template <typename T>
void CallForEachChild(const T& functor);
/**
Destroys all children of a window. Called automatically by the destructor.
*/