AspectRatioWidget.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Copyright 2018 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. // Based on:
  4. // https://stackoverflow.com/questions/30005540/keeping-the-aspect-ratio-of-a-sub-classed-qwidget-during-resize
  5. #include "DolphinQt/QtUtils/AspectRatioWidget.h"
  6. #include <QBoxLayout>
  7. #include <QResizeEvent>
  8. AspectRatioWidget::AspectRatioWidget(QWidget* widget, float width, float height, QWidget* parent)
  9. : QWidget(parent), m_ar_width(width), m_ar_height(height)
  10. {
  11. m_layout = new QBoxLayout(QBoxLayout::LeftToRight, this);
  12. // add spacer, then your widget, then spacer
  13. m_layout->addItem(new QSpacerItem(0, 0));
  14. m_layout->addWidget(widget);
  15. m_layout->addItem(new QSpacerItem(0, 0));
  16. }
  17. void AspectRatioWidget::resizeEvent(QResizeEvent* event)
  18. {
  19. float aspect_ratio = static_cast<float>(event->size().width()) / event->size().height();
  20. int widget_stretch, outer_stretch;
  21. if (aspect_ratio > (m_ar_width / m_ar_height)) // too wide
  22. {
  23. m_layout->setDirection(QBoxLayout::LeftToRight);
  24. widget_stretch = height() * (m_ar_width / m_ar_height); // i.e., my width
  25. outer_stretch = (width() - widget_stretch) / 2 + 0.5;
  26. }
  27. else // too tall
  28. {
  29. m_layout->setDirection(QBoxLayout::TopToBottom);
  30. widget_stretch = width() * (m_ar_height / m_ar_width); // i.e., my height
  31. outer_stretch = (height() - widget_stretch) / 2 + 0.5;
  32. }
  33. m_layout->setStretch(0, outer_stretch);
  34. m_layout->setStretch(1, widget_stretch);
  35. m_layout->setStretch(2, outer_stretch);
  36. }