DownloadBar.cpp raw
 1#include "DownloadBar.h"
 2#include <QHBoxLayout>
 3#include <QLabel>
 4#include <QPushButton>
 5#include <QStandardPaths>
 6#include <QVBoxLayout>
 7#include <QWebEngineDownloadRequest>
 8#include "DownloadWidget.h"
 9
10DownloadBar::DownloadBar(QWidget *parent) : QWidget(parent) {
11	auto *outer = new QVBoxLayout(this);
12	outer->setContentsMargins(0, 0, 0, 0);
13	outer->setSpacing(0);
14
15	header = new QWidget(this);
16	auto *headerLayout = new QHBoxLayout(header);
17	headerLayout->setContentsMargins(6, 2, 6, 2);
18
19	auto *title = new QLabel("Downloads", header);
20	title->setStyleSheet("font-weight: bold;");
21
22	clearButton = new QPushButton("Clear All", header);
23	clearButton->setFlat(true);
24	clearButton->setVisible(false);
25
26	headerLayout->addWidget(title);
27	headerLayout->addStretch();
28	headerLayout->addWidget(clearButton);
29
30	outer->addWidget(header);
31
32	downloadsLayout = new QVBoxLayout;
33	downloadsLayout->setContentsMargins(0, 0, 0, 0);
34	downloadsLayout->setSpacing(1);
35	outer->addLayout(downloadsLayout);
36
37	connect(clearButton, &QPushButton::clicked, this, &DownloadBar::clearCompleted);
38
39	setVisible(false);
40}
41
42void DownloadBar::addDownload(QWebEngineDownloadRequest *download) {
43	if (downloads.isEmpty()) {
44		download->setDownloadDirectory(QStandardPaths::writableLocation(QStandardPaths::DownloadLocation));
45	}
46
47	auto *widget = new DownloadWidget(download);
48	downloads.append(widget);
49	downloadsLayout->addWidget(widget);
50
51	connect(widget, &DownloadWidget::removeRequested, this, &DownloadBar::onRemoveDownload);
52
53	updateVisibility();
54}
55
56void DownloadBar::onRemoveDownload(DownloadWidget *widget) {
57	downloadsLayout->removeWidget(widget);
58	downloads.removeOne(widget);
59	widget->deleteLater();
60	updateVisibility();
61}
62
63void DownloadBar::clearCompleted() {
64	for (auto *w : QList<DownloadWidget *>(downloads)) {
65		if (w->isCompleted()) {
66			downloadsLayout->removeWidget(w);
67			downloads.removeOne(w);
68			w->deleteLater();
69		}
70	}
71	updateVisibility();
72}
73
74void DownloadBar::updateVisibility() {
75	bool hasAny = !downloads.isEmpty();
76	setVisible(hasAny);
77
78	bool hasCompleted = false;
79	for (auto *w : downloads) {
80		if (w->isCompleted()) {
81			hasCompleted = true;
82			break;
83		}
84	}
85	clearButton->setVisible(hasCompleted);
86}