1 /*
2 * This file Copyright (C) 2015 Mnemosyne LLC
3 *
4 * It may be used under the GNU GPL versions 2 or 3
5 * or any future license endorsed by Mnemosyne LLC.
6 *
7 */
8
9 #include <QApplication>
10 #include <QStyleOptionHeader>
11 #include <QStylePainter>
12
13 #include "TorrentView.h"
14
15 class TorrentView::HeaderWidget : public QWidget
16 {
17 public:
HeaderWidget(TorrentView * parent)18 HeaderWidget(TorrentView* parent) :
19 QWidget(parent),
20 myText()
21 {
22 setFont(qApp->font("QMiniFont"));
23 }
24
setText(QString const & text)25 void setText(QString const& text)
26 {
27 myText = text;
28 update();
29 }
30
31 // QWidget
sizeHint() const32 virtual QSize sizeHint() const
33 {
34 QStyleOptionHeader option;
35 option.rect = QRect(0, 0, 100, 100);
36
37 QRect const labelRect = style()->subElementRect(QStyle::SE_HeaderLabel, &option, this);
38
39 return QSize(100, fontMetrics().height() + (option.rect.height() - labelRect.height()));
40 }
41
42 protected:
43 // QWidget
paintEvent(QPaintEvent *)44 virtual void paintEvent(QPaintEvent* /*event*/)
45 {
46 QStyleOptionHeader option;
47 option.initFrom(this);
48 option.state = QStyle::State_Enabled;
49 option.position = QStyleOptionHeader::OnlyOneSection;
50
51 QStylePainter painter(this);
52 painter.drawControl(QStyle::CE_HeaderSection, option);
53
54 option.rect = style()->subElementRect(QStyle::SE_HeaderLabel, &option, this);
55 painter.drawItemText(option.rect, Qt::AlignCenter, option.palette, true, myText, QPalette::ButtonText);
56 }
57
mouseDoubleClickEvent(QMouseEvent *)58 virtual void mouseDoubleClickEvent(QMouseEvent* /*event*/)
59 {
60 emit static_cast<TorrentView*>(parent())->headerDoubleClicked();
61 }
62
63 private:
64 QString myText;
65 };
66
TorrentView(QWidget * parent)67 TorrentView::TorrentView(QWidget* parent) :
68 QListView(parent),
69 myHeaderWidget(new HeaderWidget(this))
70 {
71 }
72
setHeaderText(QString const & text)73 void TorrentView::setHeaderText(QString const& text)
74 {
75 bool const headerVisible = !text.isEmpty();
76
77 myHeaderWidget->setText(text);
78 myHeaderWidget->setVisible(headerVisible);
79
80 if (headerVisible)
81 {
82 adjustHeaderPosition();
83 }
84
85 setViewportMargins(0, headerVisible ? myHeaderWidget->height() : 0, 0, 0);
86 }
87
resizeEvent(QResizeEvent * event)88 void TorrentView::resizeEvent(QResizeEvent* event)
89 {
90 QListView::resizeEvent(event);
91
92 if (myHeaderWidget->isVisible())
93 {
94 adjustHeaderPosition();
95 }
96 }
97
adjustHeaderPosition()98 void TorrentView::adjustHeaderPosition()
99 {
100 QRect headerWidgetRect = contentsRect();
101 headerWidgetRect.setWidth(viewport()->width());
102 headerWidgetRect.setHeight(myHeaderWidget->sizeHint().height());
103 myHeaderWidget->setGeometry(headerWidgetRect);
104 }
105