-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrender.cpp
More file actions
806 lines (701 loc) · 30.8 KB
/
render.cpp
File metadata and controls
806 lines (701 loc) · 30.8 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
#include "render.h"
#include "mainwindow.h"
#include <iostream>
#include <QtCharts/QChart>
#include <QtCharts/QLineSeries>
#include <QtCharts/QValueAxis>
#include <QtCharts/QLegend> // NEW
#include <QtCharts/QChart>
#include <QtWidgets/QGraphicsScene>
#include <QtWidgets/QGraphicsView>
#include <QtCharts/QCategoryAxis>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QStringList>
#include <QGraphicsProxyWidget>
#include <QTranslator>
#include <QtCharts/QChartView>
// #include <QtCharts/QChartTheme>
#include "ui_mainwindow.h"
#include "appsettings.h" // +
// NEW
#include <cmath>
#include <QMouseEvent>
#include <QGraphicsRectItem>
#include <QGraphicsTextItem>
#include <algorithm> // NEW: for sort/min/max/clamp
#include <QApplication> // NEW
#include <QScreen> // NEW
#include <QWindow> // FIX: Include QWindow for completeness
#include <QFrame> // NEW: for setFrameShape(NoFrame)
// NEW: helper to keep the chart proxy filling the view on resize
class ViewResizeFilter : public QObject {
public:
ViewResizeFilter(QGraphicsView* v, QGraphicsProxyWidget* p)
: QObject(v), view(v), proxy(p) {
if (view->viewport()) view->viewport()->installEventFilter(this);
view->installEventFilter(this);
updateNow();
}
bool eventFilter(QObject* obj, QEvent* ev) override {
if (!view || !proxy) return QObject::eventFilter(obj, ev);
if ((obj == view || obj == view->viewport()) && ev->type() == QEvent::Resize) {
updateNow();
}
return QObject::eventFilter(obj, ev);
}
void updateNow() {
if (!view || !proxy) return;
const QRectF vpRect(0, 0, view->viewport()->width(), view->viewport()->height());
if (view->scene()) view->scene()->setSceneRect(vpRect);
proxy->setPos(0, 0);
proxy->setGeometry(vpRect);
}
private:
QGraphicsView* view = nullptr;
QGraphicsProxyWidget* proxy = nullptr;
};
// Helper: get the QChart currently shown in a QGraphicsView's scene
static QChart* chartFromGraphicsView(QGraphicsView* view) {
if (!view) return nullptr;
QGraphicsScene* scene = view->scene();
if (!scene) return nullptr;
const auto items = scene->items();
for (QGraphicsItem* gi : items) {
if (auto proxy = dynamic_cast<QGraphicsProxyWidget*>(gi)) {
if (auto cv = qobject_cast<QChartView*>(proxy->widget())) {
return cv->chart();
}
}
}
return nullptr;
}
// NEW: sélection de plage + bulle d’infos
class SelectionHandler : public QObject {
// Q_OBJECT // REMOVED: no moc needed, avoids linker errors
public:
SelectionHandler(QChartView* view, QChart* chart)
: QObject(view), view(view), chart(chart) {
// Install on the viewport (QGraphicsView delivers mouse events to viewport)
if (view && view->viewport()) {
view->viewport()->installEventFilter(this);
view->viewport()->setMouseTracking(true); // ensure move events while dragging
}
view->setMouseTracking(true);
scene = chart ? chart->scene() : nullptr;
}
bool eventFilter(QObject* obj, QEvent* ev) override {
// Only handle events coming from the viewport
if (!view || obj != view->viewport()) return QObject::eventFilter(obj, ev);
switch (ev->type()) {
case QEvent::MouseButtonPress: {
auto* me = static_cast<QMouseEvent*>(ev);
if (me->button() == Qt::LeftButton) {
pressPos = me->pos();
dragging = true;
moved = false;
ensureBand();
const double cx = mouseToChartX(pressPos);
updateBandRect(cx, cx);
return true;
}
break;
}
case QEvent::MouseMove: {
auto* me = static_cast<QMouseEvent*>(ev);
if (dragging) {
if (!moved && (me->pos() - pressPos).manhattanLength() > 3) moved = true;
const double c0 = mouseToChartX(pressPos);
const double c1 = mouseToChartX(me->pos());
updateBandRect(c0, c1);
return true;
}
break;
}
case QEvent::MouseButtonRelease: {
auto* me = static_cast<QMouseEvent*>(ev);
if (me->button() == Qt::LeftButton) {
if (!moved) {
clearVisuals(); // simple click: clear band + bubble
} else {
const QRectF plot = chart->plotArea();
const double left = std::min(selLeft, selRight);
const double right = std::max(selLeft, selRight);
if (right - left > 2.0) { // pixels in chart coords
const double xMin = chart->property("xMin").toDouble();
const double xMax = chart->property("xMax").toDouble();
const double v0 = chartXToValue(left, plot, xMin, xMax);
const double v1 = chartXToValue(right, plot, xMin, xMax);
showBubbleForRange(std::min(v0,v1), std::max(v0,v1));
}
}
dragging = false;
moved = false;
return true;
}
break;
}
default:
break;
}
return QObject::eventFilter(obj, ev);
}
private:
QChartView* view = nullptr;
QChart* chart = nullptr;
QGraphicsScene* scene = nullptr;
bool dragging = false;
bool moved = false;
QPoint pressPos;
QGraphicsRectItem* band = nullptr;
// bubble
QGraphicsRectItem* bubbleBg = nullptr;
QGraphicsTextItem* bubbleText = nullptr;
// selection bounds in chart coords (pixels relative to chart item)
double selLeft = 0.0, selRight = 0.0;
void ensureBand() {
if (!scene) return;
if (!band) {
band = scene->addRect(QRectF(), QPen(Qt::NoPen), QBrush(QColor(0,0,0,80)));
band->setZValue(1000);
}
}
void clearBubble() {
if (scene && bubbleText) { scene->removeItem(bubbleText); delete bubbleText; bubbleText = nullptr; }
if (scene && bubbleBg) { scene->removeItem(bubbleBg); delete bubbleBg; bubbleBg = nullptr; }
}
void clearBand() {
if (scene && band) { scene->removeItem(band); delete band; band = nullptr; }
}
void clearVisuals() {
clearBand();
clearBubble();
}
double mouseToChartX(const QPoint& pos) const {
const QPointF scenePt = view->mapToScene(pos);
const QPointF chartPt = chart->mapFromScene(scenePt);
return chartPt.x();
}
static double chartXToValue(double cx, const QRectF& plot, double xMinVal, double xMaxVal) {
if (plot.width() <= 0.0) return xMinVal;
const double t = std::clamp((cx - plot.left()) / plot.width(), 0.0, 1.0);
return xMinVal + t * (xMaxVal - xMinVal);
}
void updateBandRect(double x0, double x1) {
if (!scene || !chart) return;
const QRectF plot = chart->plotArea();
selLeft = x0; selRight = x1;
// Map chart coords -> scene coords for a vertical full-height band over plot
const double leftChartX = std::min(x0, x1);
const double rightChartX = std::max(x0, x1);
const QPointF plotTopLeftScene = chart->mapToScene(plot.topLeft());
const QPointF plotBottomLeftScene = chart->mapToScene(QPointF(plot.left(), plot.bottom()));
const double plotTopSceneY = plotTopLeftScene.y();
const double plotHeightScene = plotBottomLeftScene.y() - plotTopSceneY;
const double leftSceneX = chart->mapToScene(QPointF(leftChartX, plot.top())).x();
const double rightSceneX = chart->mapToScene(QPointF(rightChartX, plot.top())).x();
const double wScene = std::abs(rightSceneX - leftSceneX);
if (band) {
band->setRect(QRectF(QPointF(std::min(leftSceneX, rightSceneX), plotTopSceneY),
QSizeF(wScene, plotHeightScene)));
band->setVisible(true);
}
// moving selection hides bubble until release
clearBubble();
}
void showBubbleForRange(double xFrom, double xTo) {
if (!scene || !chart) return;
// Collect averages per series within [xFrom, xTo]
struct Row { int rank; QString name; double avg; };
QVector<Row> rows;
for (auto* s : chart->series()) {
auto* ls = qobject_cast<QLineSeries*>(s);
if (!ls) continue;
const auto pts = ls->points();
if (pts.isEmpty()) continue;
double sum = 0.0; int cnt = 0;
for (const QPointF& p : pts) {
if (p.x() >= xFrom - 1e-9 && p.x() <= xTo + 1e-9) {
sum += p.y(); cnt++;
}
}
if (cnt <= 0) continue;
const double avg = sum / cnt;
const int rank = ls->property("rank").isValid() ? ls->property("rank").toInt() : -1;
rows.push_back({ rank, ls->name(), avg });
}
std::sort(rows.begin(), rows.end(), [](const Row& a, const Row& b){
return a.avg > b.avg; // desc
});
// Header: selected time slice + percentage of total time
const double allMin = chart->property("xMin").toDouble();
const double allMax = chart->property("xMax").toDouble();
double pct = 0.0;
if (allMax > allMin + 1e-9) {
pct = ((xTo - xFrom) / (allMax - allMin)) * 100.0;
pct = std::clamp(pct, 0.0, 100.0);
}
auto formatHourLabel = [](double h)->QString {
if (h <= 0.0) return QStringLiteral("0h");
const int totalMin = qRound(h * 60.0);
const int hh = totalMin / 60;
const int mm = totalMin % 60;
return mm == 0 ? QString("%1h").arg(hh) : QString("%1h%2").arg(hh).arg(mm, 2, 10, QLatin1Char('0'));
};
QStringList lines;
lines << QString("%1 – %2 (%3%)")
.arg(formatHourLabel(std::min(xFrom, xTo)),
formatHourLabel(std::max(xFrom, xTo)),
QString::number(pct, 'f', 1));
lines << ""; // blank line above ranking
// Format rows: "#rank name : value"
for (const Row& r : rows) {
const QString left = (r.rank > 0) ? QString("#%1 %2").arg(r.rank).arg(r.name) : r.name;
lines << QString("%1 : %2").arg(left).arg(QString::number(r.avg, 'f', 2));
}
const QString text = lines.join("\n");
if (text.trimmed().isEmpty()) {
clearBubble();
return;
}
if (!bubbleText) {
bubbleText = scene->addText(QString());
bubbleText->setDefaultTextColor(Qt::white);
bubbleText->setZValue(1100);
}
bubbleText->setPlainText(text);
if (!bubbleBg) {
bubbleBg = scene->addRect(QRectF(), QPen(QColor(255,255,255,30)), QBrush(QColor(0,0,0,200)));
bubbleBg->setZValue(1090);
}
// Place bubble near right side of selection, within plot bounds
const QRectF plot = chart->plotArea();
const double leftChartX = std::min(selLeft, selRight);
const double rightChartX = std::max(selLeft, selRight);
const double rightSceneX = chart->mapToScene(QPointF(rightChartX, plot.top())).x();
const QPointF plotTopLeftScene = chart->mapToScene(plot.topLeft());
const QPointF plotTopRightScene = chart->mapToScene(plot.topRight());
const double plotLeftSceneX = plotTopLeftScene.x();
const double plotRightSceneX = plotTopRightScene.x();
const double by = plotTopLeftScene.y() + 10.0;
const QSizeF pad(12, 10);
const QRectF bb = bubbleText->boundingRect();
double bx = std::min(rightSceneX + 10.0, plotRightSceneX - (bb.width() + pad.width()));
bx = std::max(plotLeftSceneX + 6.0, bx);
bubbleText->setPos(QPointF(bx + pad.width()/2.0, by + pad.height()/2.0));
bubbleBg->setRect(QRectF(QPointF(bx, by), QSizeF(bb.width() + pad.width(), bb.height() + pad.height())));
bubbleBg->setVisible(true);
bubbleText->setVisible(true);
}
};
Render::Render() {}
// Fonction pour convertir une chaîne JSON de tableau en liste de doubles
QList<double> parseJsonArray(const QString &jsonString) {
QList<double> values;
QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());
if (!doc.isArray())
return values;
QJsonArray array = doc.array();
for (const QJsonValue &val : array) {
values.append(val.toDouble());
}
return values;
}
// Fonction pour ajuster les axes du graphique
void adjustChartAxes(QChart *chart, const QList<double> &points) {
if (points.isEmpty()) return;
double minY = *std::min_element(points.begin(), points.end());
double maxY = *std::max_element(points.begin(), points.end());
if (minY < 0) minY = 0;
double margin = (maxY - minY) * 0.06; // 6% margin (slightly lower)
if (margin <= 0) margin = 1.0;
maxY += margin;
// Replace vertical axis with a numeric axis for perfect alignment
auto axisY = new QValueAxis();
axisY->setRange(minY, maxY);
axisY->setTickCount(7);
axisY->setLabelFormat("%.0f");
// Remove old vertical axis and attach new one
const auto vAxes = chart->axes(Qt::Vertical);
if (!vAxes.isEmpty()) chart->removeAxis(vAxes.first());
chart->addAxis(axisY, Qt::AlignLeft);
if (!chart->series().isEmpty()) chart->series().first()->attachAxis(axisY);
}
// Even-ticks Y axis for wins_pace: 0, 2, 4, ..., topEven
static void adjustChartAxesEvenWinsPace(QChart* chart, const QList<double>& points) {
if (points.isEmpty()) return;
double maxY = *std::max_element(points.begin(), points.end());
if (maxY < 0.0) maxY = 0.0;
int topEven = static_cast<int>(std::ceil(maxY));
if (topEven < 2) topEven = 2;
if (topEven % 2 != 0) ++topEven; // ensure even
auto axisY = new QCategoryAxis();
axisY->setRange(0.0, static_cast<double>(topEven));
axisY->setLabelsPosition(QCategoryAxis::AxisLabelsPositionOnValue);
for (int v = 0; v <= topEven; v += 2) {
axisY->append(QString::number(v), static_cast<double>(v));
}
const auto vAxes = chart->axes(Qt::Vertical);
if (!vAxes.isEmpty()) chart->removeAxis(vAxes.first());
chart->addAxis(axisY, Qt::AlignLeft);
if (!chart->series().isEmpty()) chart->series().first()->attachAxis(axisY);
}
void adjustChartAxes_leaderboard(QChart *chart, const QList<double> &points) {
if (points.isEmpty()) return;
// Plage Y: commence à 0, ajoute une marge haute
double minY = 0.0;
double maxY = *std::max_element(points.begin(), points.end());
double margin = (maxY - minY) * 0.06; // 6% margin (slightly lower)
maxY += margin;
// Axe Y en catégories, labels posés sur les traits
auto axisY = new QCategoryAxis();
axisY->setRange(minY, maxY);
axisY->setLabelsPosition(QCategoryAxis::AxisLabelsPositionOnValue); // NEW
// Ticks tous les 2 (0,2,4,...) jusqu'au max visible
const int topEven = static_cast<int>(std::ceil(maxY / 2.0)) * 2;
for (int v = 0; v <= topEven; v += 2) {
axisY->append(QString::number(v), static_cast<double>(v));
}
// Remplace l’axe vertical par le nouvel axe
const auto vAxes = chart->axes(Qt::Vertical);
if (!vAxes.isEmpty()) chart->removeAxis(vAxes.first());
chart->addAxis(axisY, Qt::AlignLeft);
if (!chart->series().isEmpty()) chart->series().first()->attachAxis(axisY);
}
// Fonction pour créer et afficher un graphique dans un QGraphicsView
void Render::createLineChartInGraphicsView(Ui::MainWindow *ui, const QString &hoursStr, const QString &pointsStr, const QString& elementKey) {
// Conversion des chaînes JSON en listes de valeurs
QList<double> hours = parseJsonArray(hoursStr);
QList<double> points = parseJsonArray(pointsStr);
// Vérification que les listes ont la même taille
if (hours.size() != points.size()) {
qWarning("Les tailles des données ne correspondent pas !");
// std::cout << hours.size() << " " << points.size() << std::endl;
return;
}
// Création d'une série pour le graphique en ligne
QLineSeries *series = new QLineSeries();
for (int i = 0; i < hours.size(); ++i) {
series->append(hours[i], points[i]);
}
// Création du graphique
QChart *chart = new QChart();
chart->addSeries(series);
chart->setTitle("\""+ui->ydataBox->currentText() +QObject::tr("\" en fonction des heures"));
chart->createDefaultAxes();
chart->axes(Qt::Horizontal).first()->setTitleText(QObject::tr("Heures"));
chart->axes(Qt::Vertical).first()->setTitleText(QObject::tr("Points"));
chart->setAnimationOptions(QChart::SeriesAnimations);
// Appliquer le thème
chart->setTheme(AppSettings::chartThemeEnum());
chart->setMargins(QMargins(12, 8, 8, 14));
// NEW: keep theme background and rounded corners, but remove the border pen (black contour)
chart->setBackgroundPen(Qt::NoPen);
// Ajuster l’axe Y: even ticks for wins_pace, else numeric auto
if (elementKey == QStringLiteral("wins_pace")) {
adjustChartAxesEvenWinsPace(chart, points);
} else {
adjustChartAxes(chart, points);
}
// NEW: Axe X personnalisé en heures (catégories à 6h ou 12h)
if (!hours.isEmpty()) {
const double minX = hours.first();
const double maxX = hours.last();
const double span = std::max(0.0, maxX - minX);
const double step = (span <= 36.0 ? 6.0 : 12.0);
auto axisX = new QCategoryAxis();
axisX->setRange(minX, maxX);
axisX->setLabelsPosition(QCategoryAxis::AxisLabelsPositionOnValue);
if (minX <= 0.0) axisX->append(QStringLiteral("0h"), 0.0);
double start = std::ceil((minX > 0.0 ? minX : 0.0) / step) * step;
for (double v = start; v <= maxX + 1e-6; v += step) {
axisX->append(QString::number(v, 'f', 0) + "h", v);
}
// Remplacer l’axe horizontal par le nouvel axe
const auto hAxes = chart->axes(Qt::Horizontal);
for (auto a : hAxes) chart->removeAxis(a);
chart->addAxis(axisX, Qt::AlignBottom);
if (!chart->series().isEmpty()) chart->series().first()->attachAxis(axisX);
}
// Prepare view/scene
QGraphicsView *view = ui->graphiqueTest;
if (!view->scene()) {
view->setScene(new QGraphicsScene(view));
}
QGraphicsScene* scene = view->scene();
scene->clear();
// NEW: transparent scene to avoid dark halo around rounded corners
scene->setBackgroundBrush(Qt::NoBrush);
// Disable scrollbars and borders
view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
view->setFrameShape(QFrame::NoFrame);
view->setBackgroundBrush(Qt::NoBrush);
view->setStyleSheet("border: 0;");
// NEW: make the viewport transparent
if (view->viewport()) {
view->viewport()->setAutoFillBackground(false);
view->viewport()->setStyleSheet("background: transparent;");
}
QRectF vpRect(0, 0, view->viewport()->width(), view->viewport()->height());
scene->setSceneRect(vpRect);
auto chartView = new QChartView(chart);
chartView->setFrameShape(QFrame::NoFrame);
chartView->setLineWidth(0);
chartView->setContentsMargins(0, 0, 0, 0);
chartView->setRenderHint(QPainter::Antialiasing);
chartView->setStyleSheet("border: 0;");
// NEW: ensure chart view is transparent outside the chart rounded corners
chartView->setAutoFillBackground(false);
chartView->setBackgroundBrush(Qt::NoBrush);
chartView->setAttribute(Qt::WA_TranslucentBackground);
if (chartView->viewport()) {
chartView->viewport()->setAutoFillBackground(false);
chartView->viewport()->setAttribute(Qt::WA_TranslucentBackground);
}
QGraphicsProxyWidget *proxy = scene->addWidget(chartView);
proxy->setPos(0, 0);
proxy->setGeometry(vpRect);
new ViewResizeFilter(view, proxy);
view->setRenderHint(QPainter::Antialiasing);
view->show();
}
void Render::render_leaderboard(MainWindow *this_, QGraphicsView *graphPlaceholder, const QString &hoursStr, const QString &pointsStr, const QString element, const QString &name, int rank)
{
// Conversion des chaînes JSON en listes de valeurs
QList<double> hours = parseJsonArray(hoursStr);
QList<double> points = parseJsonArray(pointsStr);
// Vérification que les listes ont la même taille
if (hours.size() != points.size()) {
qWarning("Les tailles des données ne correspondent pas !");
// std::cout << hours.size() << " " << points.size() << std::endl;
return;
}
// Création d'une série pour le graphique en ligne
QLineSeries *series = new QLineSeries();
for (int i = 0; i < hours.size(); ++i) {
series->append(hours[i], points[i]);
}
series->setName(name); // base series named after the player
series->setProperty("rank", rank); // NEW: store rank for later display
// Création du graphique
QChart *chart = new QChart();
chart->addSeries(series);
chart->setTitle(name + " : " + "\""+element +QObject::tr("\" en fonction des heures"));
chart->createDefaultAxes();
chart->axes(Qt::Horizontal).first()->setTitleText(QObject::tr("Heures"));
chart->axes(Qt::Vertical).first()->setTitleText(QObject::tr("Points"));
chart->setAnimationOptions(QChart::SeriesAnimations);
chart->legend()->setVisible(false);
chart->legend()->setBackgroundVisible(false);
chart->legend()->setAlignment(Qt::AlignBottom);
chart->legend()->setMarkerShape(QLegend::MarkerShapeFromSeries);
chart->setTheme(AppSettings::chartThemeEnum());
chart->setMargins(QMargins(12, 8, 8, 14));
// NEW: remove chart border pen (prevents black outline) while keeping themed background
chart->setBackgroundPen(Qt::NoPen);
// Ajuster l'axe Y
adjustChartAxes_leaderboard(chart, points);
// NEW: Axe X personnalisé en heures (catégories à 6h ou 12h)
if (!hours.isEmpty()) {
const double minX = hours.first();
const double maxX = hours.last();
const double span = std::max(0.0, maxX - minX);
const double step = (span <= 36.0 ? 6.0 : 12.0);
auto axisX = new QCategoryAxis();
axisX->setRange(minX, maxX);
axisX->setLabelsPosition(QCategoryAxis::AxisLabelsPositionOnValue);
// Ajoute 0h si visible
if (minX <= 0.0) axisX->append(QStringLiteral("0h"), 0.0);
// Première étiquette alignée sur un multiple de 'step'
double start = std::ceil((minX > 0.0 ? minX : 0.0) / step) * step;
for (double v = start; v <= maxX + 1e-6; v += step) {
axisX->append(QString::number(v, 'f', 0) + "h", v);
}
// Remplace l’axe horizontal par le nouvel axe
const auto hAxes = chart->axes(Qt::Horizontal);
for (auto a : hAxes) chart->removeAxis(a);
chart->addAxis(axisX, Qt::AlignBottom);
if (!chart->series().isEmpty()) chart->series().first()->attachAxis(axisX);
}
// NEW: mémoriser la plage X pour le mapping (utilisée par la sélection)
if (!hours.isEmpty()) {
const double minX = hours.first();
const double maxX = hours.last();
chart->setProperty("xMin", minX);
chart->setProperty("xMax", maxX);
}
// Ensure a scene exists and is empty
if (!graphPlaceholder->scene()) {
graphPlaceholder->setScene(new QGraphicsScene(graphPlaceholder));
}
QGraphicsScene *scene = graphPlaceholder->scene();
scene->clear();
// NEW: transparent scene
scene->setBackgroundBrush(Qt::NoBrush);
graphPlaceholder->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
graphPlaceholder->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
graphPlaceholder->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
graphPlaceholder->setFrameShape(QFrame::NoFrame);
graphPlaceholder->setBackgroundBrush(Qt::NoBrush);
graphPlaceholder->setStyleSheet("border: 0;");
// NEW: transparent viewport
if (graphPlaceholder->viewport()) {
graphPlaceholder->viewport()->setAutoFillBackground(false);
graphPlaceholder->viewport()->setStyleSheet("background: transparent;");
}
QRectF vpRect(0, 0, graphPlaceholder->viewport()->width(), graphPlaceholder->viewport()->height());
scene->setSceneRect(vpRect);
auto chartView = new QChartView(chart);
chartView->setFrameShape(QFrame::NoFrame);
chartView->setLineWidth(0);
chartView->setContentsMargins(0, 0, 0, 0);
chartView->setRenderHint(QPainter::Antialiasing);
chartView->setMouseTracking(true);
if (chartView->viewport()) chartView->viewport()->setMouseTracking(true);
chartView->setStyleSheet("border: 0;");
// NEW: transparent outside rounded corners
chartView->setAutoFillBackground(false);
chartView->setBackgroundBrush(Qt::NoBrush);
chartView->setAttribute(Qt::WA_TranslucentBackground);
if (chartView->viewport()) {
chartView->viewport()->setAutoFillBackground(false);
chartView->viewport()->setAttribute(Qt::WA_TranslucentBackground);
}
QGraphicsProxyWidget *proxy = scene->addWidget(chartView);
proxy->setPos(0, 0);
proxy->setGeometry(vpRect);
new ViewResizeFilter(graphPlaceholder, proxy);
// Activate selection handler (install on viewport)
if (!chartView->property("selectionHandler").toBool()) {
new SelectionHandler(chartView, chart); // parented to chartView
chartView->setProperty("selectionHandler", true);
}
graphPlaceholder->setRenderHint(QPainter::Antialiasing);
graphPlaceholder->show();
}
// NEW: snapshot helper
QImage Render::grabChartImage(QGraphicsView* view)
{
if (!view) return QImage();
// Ensure something is displayed
if (!view->scene() || view->scene()->items().isEmpty()) return QImage();
const QSize vpSize = view->viewport()->size();
if (vpSize.isEmpty()) return QImage();
qreal dpr = 1.0;
if (view->windowHandle() && view->windowHandle()->screen())
dpr = view->windowHandle()->screen()->devicePixelRatio();
QImage img(vpSize * dpr, QImage::Format_ARGB32_Premultiplied);
img.setDevicePixelRatio(dpr);
img.fill(Qt::transparent);
QPainter p(&img);
view->render(&p); // renders the viewport (chart + overlays)
p.end();
return img;
}
// NEW: crop render to chart area and composite on opaque background to avoid borders
QImage Render::grabChartOnly(QGraphicsView* view)
{
if (!view || !view->scene()) return QImage();
// Locate the embedded QChartView and its QChart
QChartView* chartView = nullptr;
QChart* chart = nullptr;
for (QGraphicsItem* gi : view->scene()->items()) {
if (auto proxy = dynamic_cast<QGraphicsProxyWidget*>(gi)) {
if (auto cv = qobject_cast<QChartView*>(proxy->widget())) {
chartView = cv;
chart = cv->chart();
break;
}
}
}
if (!chartView || !chart) return QImage();
// Exact chart rect inside the QChartView
const QRectF chartRectF = chart->geometry();
const QRect chartRect = chartRectF.toRect();
if (chartRect.isEmpty()) return QImage();
// Target DPR
qreal dpr = 1.0;
if (view->windowHandle() && view->windowHandle()->screen())
dpr = view->windowHandle()->screen()->devicePixelRatio();
// Prepare an opaque image filled with the chart background color (no transparent corners)
QColor bg = chart->backgroundBrush().color();
if (!bg.isValid()) bg = chartView->palette().window().color();
bg.setAlpha(255);
const QSize outSize(qMax(1, int(std::round(chartRect.width() * dpr))),
qMax(1, int(std::round(chartRect.height() * dpr))));
QImage img(outSize, QImage::Format_ARGB32_Premultiplied);
img.setDevicePixelRatio(dpr);
img.fill(bg.rgba());
QPainter p(&img);
p.setRenderHint(QPainter::Antialiasing, true);
// Render only the chart area from the chartView onto our opaque image
const QRectF target(QPointF(0, 0), QSizeF(chartRect.size()));
chartView->render(&p, target, chartRect); // FIX: third arg must be QRect
p.end();
return img;
}
// NEW: add an extra line series to the existing chart inside a QGraphicsView
bool Render::addSeriesToExistingChart(QGraphicsView *view, const QString &hoursStr, const QString &pointsStr, const QString &seriesName, int rank)
{
QChart* chart = chartFromGraphicsView(view);
if (!chart) return false;
QList<double> hours = parseJsonArray(hoursStr);
QList<double> points = parseJsonArray(pointsStr);
if (hours.size() != points.size() || hours.isEmpty()) return false;
// Avoid duplicates by name
for (auto s : chart->series()) {
if (s->name() == seriesName) return false;
}
auto s = new QLineSeries();
s->setName(seriesName);
s->setProperty("rank", rank); // NEW: store rank
for (int i = 0; i < hours.size(); ++i) s->append(hours[i], points[i]);
chart->addSeries(s);
// Attach to existing axes
if (!chart->axes(Qt::Horizontal).isEmpty()) s->attachAxis(chart->axes(Qt::Horizontal).first());
if (!chart->axes(Qt::Vertical).isEmpty()) s->attachAxis(chart->axes(Qt::Vertical).first());
chart->legend()->setBackgroundVisible(false);
chart->legend()->setAlignment(Qt::AlignBottom);
chart->legend()->setMarkerShape(QLegend::MarkerShapeFromSeries);
chart->legend()->setVisible(chart->series().size() > 1);
return true;
}
// NEW: remove a series by its name (does not remove the base if name matches it is allowed)
bool Render::removeSeriesByName(QGraphicsView *view, const QString &seriesName)
{
QChart* chart = chartFromGraphicsView(view);
if (!chart) return false;
for (auto s : chart->series()) {
if (s->name() == seriesName) {
chart->removeSeries(s);
delete s;
chart->legend()->setVisible(chart->series().size() > 1);
return true;
}
}
return false;
}
// NEW: clear all overlays (keep base if it exists and matches baseSeriesName)
void Render::clearAllOverlaySeries(QGraphicsView *view, const QString &baseSeriesName)
{
QChart* chart = chartFromGraphicsView(view);
if (!chart) return;
// Collect to remove: all that are not the base
QList<QAbstractSeries*> toRemove;
for (auto s : chart->series()) {
if (s->name() != baseSeriesName) toRemove.append(s);
}
for (auto s : toRemove) {
chart->removeSeries(s);
delete s;
}
chart->legend()->setVisible(chart->series().size() > 1);
}
// NEW: public wrapper
QChart* Render::chartFromView(QGraphicsView* view)
{
return chartFromGraphicsView(view);
}