blob: 9a5f81c2556fd51492339db02c1e536e0269de62 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
#ifndef ASPECTRATIOWIDGET_HPP
#define ASPECTRATIOWIDGET_HPP
#include <QWidget>
#include <QBoxLayout>
class AspectRatioWidget : public QWidget
{
Q_OBJECT
public:
AspectRatioWidget(QWidget *parent = 0) : QWidget(parent)
{
m_layout = new QHBoxLayout();
m_layout->setSpacing(0);
m_layout->setContentsMargins(0, 0, 0, 0);
setLayout(m_layout);
}
// the widget we want to keep the ratio
void setAspectWidget(QWidget* widget, const double ratio = 1.0) {
m_aspect_widget = widget;
m_layout->addWidget(widget);
m_ratio = ratio;
}
void setRatio(const double ratio) {
m_ratio = ratio;
applyAspectRatio();
}
protected:
void resizeEvent(QResizeEvent *event) {
(void)event;
applyAspectRatio();
}
public slots:
void applyAspectRatio() {
int w = this->width();
int h = this->height();
double aspect = static_cast<double>(h)/static_cast<double>(w);
if(aspect < m_ratio) // parent is too wide
{
int target_width = static_cast<int>(static_cast<double>(h)/m_ratio);
m_aspect_widget->setMaximumWidth(target_width);
m_aspect_widget->setMaximumHeight(h);
}
else // parent is too high
{
int target_heigth = static_cast<int>(static_cast<double>(w)*m_ratio);
m_aspect_widget->setMaximumHeight(target_heigth);
m_aspect_widget->setMaximumWidth(w);
}
}
private:
QHBoxLayout* m_layout;
QWidget* m_aspect_widget;
double m_ratio;
};
#endif // ASPECTRATIOWINDOW_H
|