Debian Codegraph @

examples/dnd-example/dnd-test-server.cpp

raw
1 // SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd.
2 //
3 // SPDX-License-Identifier: LGPL-3.0-or-later
4
5 #include "dfiledragserver.h"
6 #include "dfiledrag.h"
7
8 #include <QDialog>
9 #include <QLabel>
10 #include <QTimer>
11 #include <QMimeData>
12 #include <QApplication>
13 #include <QMouseEvent>
14 #include <QVBoxLayout>
15 #include <QProgressBar>
16 #include <QDebug>
17 #include <QRandomGenerator>
18
19 DGUI_USE_NAMESPACE
20
21 static int p;
22 static DFileDragServer *s = nullptr;
23 static QLabel *lbr = nullptr;
24
25 class DraggableLabel : public QLabel
26 {
27 Q_OBJECT
28 public:
29 using QLabel::QLabel;
30
31 Q_SIGNALS:
32 void dragFinished();
33
34 protected:
35 void mousePressEvent(QMouseEvent *e)
36 {
37 if (e->button() == Qt::MouseButton::LeftButton) {
38 dragpos = e->pos();
39 }
40 }
41
42 void mouseMoveEvent(QMouseEvent *e)
43 {
44 if (!(e->buttons() & Qt::MouseButton::LeftButton) || s) {
45 return;
46 }
47 if ((e->pos() - dragpos).manhattanLength() < QApplication::startDragDistance()) {
48 return;
49 }
50
51 s = new DFileDragServer();
52 DFileDrag *drag = new DFileDrag(this, s);
53 QMimeData *m = new QMimeData();
54 m->setText("your stuff here");
55 drag->setMimeData(m);
56
57 connect(drag, &DFileDrag::targetUrlChanged, [drag] {
58 lbr->setText(drag->targetUrl().toString());
59 });
60
61 Qt::DropAction res = drag->exec(Qt::MoveAction);
62 if (res!= Qt::IgnoreAction)
63 Q_EMIT dragFinished();
64 else {
65 s->deleteLater();
66 s = nullptr;
67 }
68 }
69
70 private:
71 QPoint dragpos;
72 };
73
74 int main(int argc, char **argv)
75 {
76 QApplication a(argc, argv);
77 QDialog d;
78 d.show();
79
80 DraggableLabel l("Drag me", &d);
81 l.setAlignment(Qt::AlignCenter);
82
83 QTimer t;
84 t.setInterval(50);
85 t.setSingleShot(false);
86
87 QProgressBar pg;
88 pg.setMinimum(0);
89 pg.setMaximum(100);
90
91 QLabel lb;
92 lbr = &lb;
93 lb.setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
94
95 QObject::connect(&l, &DraggableLabel::dragFinished, [&t] {
96 p = -1;
97 t.start();
98 });
99
100 QObject::connect(&t, &QTimer::timeout, [&t, &pg] {
101 if (QRandomGenerator::global()->generate() & 1) {
102 s->setProgress(++p);
103 pg.setValue(p);
104 if(p == 100) {
105 t.stop();
106 s->deleteLater();
107 s = nullptr;
108 }
109 }
110 });
111
112 QVBoxLayout lo;
113 lo.addWidget(&l);
114 lo.addWidget(&pg);
115 lo.addWidget(&lb);
116 d.setLayout(&lo);
117
118 a.exec();
119 }
120
121 #include "dnd-test-server.moc"