theme optional in layout and don't do layout automatically on every widget addition

This commit is contained in:
Andrea Blankenstijn 2022-02-05 19:20:40 +01:00
parent 72dd10ef06
commit 01932cee20
2 changed files with 20 additions and 13 deletions

View file

@ -26,6 +26,10 @@ namespace bwidgets
{
if (renderer()) widget_ptr->renderer(renderer());
_widgets.emplace_back(std::move(widget_ptr));
}
void do_layout() override
{
_handle_geometry_change(viewport());
}
@ -42,6 +46,9 @@ namespace bwidgets
// Return smallest usable size.
[[nodiscard]] auto size() const noexcept -> Size override
{
const auto margins {
theme() ? theme()->size_layout_margin() : Size {4, 4}
};
Size min_size {0, 0};
if constexpr (alignment == LayoutAlignment::HORIZONTAL) {
@ -51,8 +58,8 @@ namespace bwidgets
});
return {(int)_widgets.size() * min_size.w
+ ((int)_widgets.size() + 1) * theme()->size_layout_margin().w,
min_size.h + 2 * theme()->size_layout_margin().h};
+ ((int)_widgets.size() + 1) * margins.w,
min_size.h + 2 * margins.h};
}
// Vertical
@ -62,9 +69,8 @@ namespace bwidgets
min_size.h += w->size().h;
});
return {min_size.w + 2 * theme()->size_layout_margin().w,
min_size.h
+ ((int)_widgets.size() + 1) * theme()->size_layout_margin().h};
return {min_size.w + 2 * margins.w,
min_size.h + ((int)_widgets.size() + 1) * margins.h};
}
private:
@ -72,18 +78,18 @@ namespace bwidgets
void _handle_geometry_change(const SDL_Rect& vp) override
{
const auto margins {
theme() ? theme()->size_layout_margin() : Size {4, 4}
};
if constexpr (alignment == LayoutAlignment::HORIZONTAL) {
const int widget_width =
(vp.w - ((int)_widgets.size() + 1) * theme()->size_layout_margin().w)
/ (int)_widgets.size();
(vp.w - ((int)_widgets.size() + 1) * margins.w) / (int)_widgets.size();
for (std::vector<Widget*>::size_type i = 0; i < _widgets.size(); i++) {
const auto& w {_widgets[i]};
w->viewport(
{vp.x + theme()->size_layout_margin().w
+ (int)i * (widget_width + theme()->size_layout_margin().w),
vp.y + center_line(vp.h, w->size().h), widget_width,
w->size().h});
w->viewport({vp.x + margins.w + (int)i * (widget_width + margins.w),
vp.y + center_line(vp.h, w->size().h), widget_width,
w->size().h});
}
}
else { // Vertical
@ -92,7 +98,7 @@ namespace bwidgets
const auto& w {_widgets[i]};
w->viewport({
vp.x,
vp.y + ((int)i + 1) * theme()->size_layout_margin().h + offset,
vp.y + ((int)i + 1) * margins.h + offset,
vp.w,
w->size().h,
});

View file

@ -11,6 +11,7 @@ namespace bwidgets
public:
// Add widget to the layout
virtual void add_widget(std::shared_ptr<Widget>) = 0;
virtual void do_layout() = 0;
// Apply a function to every layout widget.
virtual void for_widgets(const std::function<void(Widget*)>&) = 0;
virtual void for_widgets(const std::function<void(const Widget*)>&) const = 0;