Debian Codegraph @

tests/manual/highdpi/kitchensink/main.cpp

raw
1 // Copyright (C) 2016 The Qt Company Ltd.
2 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3
4 #include <QMainWindow>
5 #include <QMenuBar>
6 #include <QLabel>
7 #include <QHBoxLayout>
8 #include <QFormLayout>
9 #include <QApplication>
10 #include <QAction>
11 #include <QStyle>
12 #include <QToolBar>
13 #include <QPushButton>
14 #include <QButtonGroup>
15 #include <QLineEdit>
16 #include <QPlainTextEdit>
17 #include <QTabWidget>
18 #include <QScrollBar>
19 #include <QSlider>
20 #include <QSpinBox>
21 #include <QTabBar>
22 #include <QTextBrowser>
23 #include <QIcon>
24 #include <QPainter>
25 #include <QWindow>
26 #include <QScreen>
27 #include <QGraphicsView>
28 #include <QGraphicsTextItem>
29 #include <QFile>
30 #include <QFontMetrics>
31 #include <QMouseEvent>
32 #include <QTemporaryDir>
33 #include <QTimer>
34 #include <QCommandLineParser>
35 #include <QCommandLineOption>
36 #include <QDebug>
37 #include <QElapsedTimer>
38 #include <private/qhighdpiscaling_p.h>
39 #include <qpa/qplatformscreen.h>
40
41 #include "dragwidget.h"
42
43 #include <utility>
44
45 static QTextStream &operator<<(QTextStream &str, const QSizeF &s)
46 {
47 str << s.width() << 'x' << s.height();
48 return str;
49 }
50
51 static QTextStream &operator<<(QTextStream &str, const QRect &r)
52 {
53 str << r.width() << 'x' << r.height() << Qt::forcesign << r.x() << r.y() << Qt::noforcesign;
54 return str;
55 }
56
57 static QString formatWindowTitle(const QString &title)
58 {
59 QString result;
60 QTextStream(&result) << title << ' ' << QT_VERSION_STR << " ("
61 << QGuiApplication::platformName()
62 << '/' << QApplication::style()->objectName() << ')';
63 return result;
64 }
65
66 class DemoContainerBase
67 {
68 public:
69 DemoContainerBase() = default;
70 virtual ~DemoContainerBase() = default;
71 QString name() { return option().names().constFirst(); }
72 virtual QCommandLineOption &option() = 0;
73 virtual void makeVisible(bool visible, QWidget *parent) = 0;
74 QWidget *widget() const { return m_widget; }
75
76 protected:
77 QWidget *m_widget = nullptr;
78 };
79
80 using DemoContainerList = QList<DemoContainerBase*>;
81
82 template <class T>
83 class DemoContainer : public DemoContainerBase
84 {
85 public:
86 DemoContainer(const QString &optionName, const QString &description)
87 : m_option(optionName, description)
88 {
89 }
90 ~DemoContainer() { delete m_widget; }
91
92 QCommandLineOption &option() override { return m_option; }
93
94 void makeVisible(bool visible, QWidget *parent) override
95 {
96 if (visible && !m_widget) {
97 m_widget = new T;
98 if (m_widget->windowTitle().isEmpty()) {
99 QString title = m_option.description();
100 if (title.startsWith("Test ", Qt::CaseInsensitive))
101 title.remove(0, 5);
102 title[0] = title.at(0).toUpper();
103 m_widget->setWindowTitle(formatWindowTitle(title));
104 }
105 m_widget->installEventFilter(parent);
106 }
107 if (m_widget)
108 m_widget->setVisible(visible);
109 }
110
111 private:
112 QCommandLineOption m_option;
113 };
114
115 class LabelSlider : public QObject
116 {
117 Q_OBJECT
118 public:
119 LabelSlider(QObject *parent, const QString &text, QGridLayout *layout, int row)
120 : QObject(parent)
121 {
122 QLabel *textLabel = new QLabel(text);
123 m_slider = new QSlider();
124 m_slider->setOrientation(Qt::Horizontal);
125 m_slider->setMinimum(1);
126 m_slider->setMaximum(40);
127 m_slider->setValue(10);
128 m_slider->setTracking(false);
129 m_slider->setTickInterval(5);
130 m_slider->setTickPosition(QSlider::TicksBelow);
131 m_label = new QLabel("1.0");
132
133 // set up layouts
134 layout->addWidget(textLabel, row, 0);
135 layout->addWidget(m_slider, row, 1);
136 layout->addWidget(m_label, row, 2);
137
138 // handle slider position change
139 connect(m_slider, &QSlider::sliderMoved, this, &LabelSlider::updateLabel);
140 connect(m_slider, &QSlider::valueChanged, this, &LabelSlider::valueChanged);
141 }
142 void setValue(int scaleFactor)
143 {
144 m_slider->setValue(scaleFactor);
145 updateLabel(scaleFactor);
146 }
147
148 private slots:
149 void updateLabel(int scaleFactor)
150 {
151 // slider value is scale factor times ten;
152 qreal scalefactorF = qreal(scaleFactor) / 10.0;
153
154 // update label, add ".0" if needed.
155 QString number = QString::number(scalefactorF);
156 if (!number.contains(QLatin1Char('.')))
157 number.append(".0");
158 m_label->setText(number);
159 }
160
161 signals:
162 void valueChanged(int scaleFactor);
163
164 private:
165 QSlider *m_slider;
166 QLabel *m_label;
167 };
168
169 static qreal getScreenFactorWithoutPixelDensity(const QScreen *screen)
170 {
171 // this is a hack that relies on knowing the internals of QHighDpiScaling
172 static const char *scaleFactorProperty = "_q_scaleFactor";
173 QVariant screenFactor = screen->property(scaleFactorProperty);
174 return screenFactor.isValid() ? screenFactor.toReal() : 1.0;
175 }
176
177 static inline qreal getGlobalScaleFactor()
178 {
179 QScreen *noScreen = nullptr;
180 return QHighDpiScaling::factor(noScreen);
181 }
182
183 class DemoController : public QWidget
184 {
185 Q_OBJECT
186 public:
187 DemoController(DemoContainerList demos, QCommandLineParser *parser);
188 ~DemoController();
189
190 protected:
191 bool eventFilter(QObject *object, QEvent *event) override;
192 void closeEvent(QCloseEvent *) override { QCoreApplication::quit(); }
193
194 private slots:
195 void handleButton(int id, bool toggled);
196
197 private:
198 DemoContainerList m_demos;
199 QButtonGroup *m_group;
200 };
201
202 DemoController::DemoController(DemoContainerList demos, QCommandLineParser *parser)
203 : m_demos(std::move(demos))
204 {
205 setWindowTitle(formatWindowTitle("Screen Scale Factors"));
206 setObjectName("controller"); // make WindowScaleFactorSetter skip this window
207
208 auto mainLayout = new QVBoxLayout(this);
209 auto scaleLayout = new QGridLayout;
210 mainLayout->addLayout(scaleLayout);
211
212 int layoutRow = 0;
213 LabelSlider *globalScaleSlider = new LabelSlider(this, "Global scale factor", scaleLayout, layoutRow++);
214 globalScaleSlider->setValue(int(getGlobalScaleFactor() * 10));
215 connect(globalScaleSlider, &LabelSlider::valueChanged, [](int scaleFactor){
216 // slider value is scale factor times ten;
217 qreal scalefactorF = qreal(scaleFactor) / 10.0;
218 QHighDpiScaling::setGlobalFactor(scalefactorF);
219 });
220
221 // set up one scale control line per screen
222 const auto screens = QGuiApplication::screens();
223 for (QScreen *screen : screens) {
224 // create scale control line
225 QSize screenSize = screen->geometry().size();
226 QString screenId = screen->name() + QLatin1Char(' ') + QString::number(screenSize.width())
227 + QLatin1Char(' ') + QString::number(screenSize.height());
228 LabelSlider *slider = new LabelSlider(this, screenId, scaleLayout, layoutRow++);
229 slider->setValue(getScreenFactorWithoutPixelDensity(screen) * 10);
230
231 // handle slider value change
232 connect(slider, &LabelSlider::valueChanged, [screen](int scaleFactor){
233 // slider value is scale factor times ten;
234 qreal scalefactorF = qreal(scaleFactor) / 10.0;
235
236 // set scale factor for screen
237 qreal oldFactor = QHighDpiScaling::factor(screen);
238 QHighDpiScaling::setScreenFactor(screen, scalefactorF);
239 qreal newFactor = QHighDpiScaling::factor(screen);
240
241 qDebug() << "factor was / is" << oldFactor << newFactor;
242 });
243 }
244
245 auto demoLayout = new QFormLayout;
246 mainLayout->addLayout(demoLayout);
247 m_group = new QButtonGroup(this);
248 m_group->setExclusive(false);
249
250 for (int i = 0; i < m_demos.size(); ++i) {
251 DemoContainerBase *demo = m_demos.at(i);
252 QString name = demo->name();
253 name[0] = name.at(0).toUpper();
254 auto button = new QPushButton(name);
255 button->setCheckable(true);
256 demoLayout->addRow(demo->option().description(), button);
257 m_group->addButton(button, i);
258
259 if (parser->isSet(demo->option())) {
260 demo->makeVisible(true, this);
261 button->setChecked(true);
262 }
263 }
264 connect(m_group, &QButtonGroup::idToggled,
265 this, &DemoController::handleButton);
266 }
267
268 DemoController::~DemoController()
269 {
270 qDeleteAll(m_demos);
271 }
272
273 bool DemoController::eventFilter(QObject *object, QEvent *event)
274 {
275 if (event->type() == QEvent::Close) {
276 for (int i = 0; i < m_demos.size(); ++i) {
277 DemoContainerBase *demo = m_demos.at(i);
278 if (demo->widget() == object) {
279 m_group->button(i)->setChecked(false);
280 break;
281 }
282 }
283 }
284 return false;
285 }
286
287 void DemoController::handleButton(int id, bool toggled)
288 {
289 m_demos.at(id)->makeVisible(toggled, this);
290 }
291
292 class PixmapPainter : public QWidget
293 {
294 public:
295 PixmapPainter();
296
297 void paintEvent(QPaintEvent *event) override;
298
299 private:
300 QPixmap pixmap1X;
301 QPixmap pixmap2X;
302 QPixmap pixmapLarge;
303 QImage image1X;
304 QImage image2X;
305 QImage imageLarge;
306 QIcon qtIcon;
307 };
308
309 PixmapPainter::PixmapPainter()
310 {
311 pixmap1X = QPixmap(":/qticon32.png");
312 pixmap2X = QPixmap(":/[email protected]");
313 pixmapLarge = QPixmap(":/qticon64.png");
314
315 image1X = QImage(":/qticon32.png");
316 image2X = QImage(":/[email protected]");
317 imageLarge = QImage(":/qticon64.png");
318
319 qtIcon.addFile(":/qticon32.png");
320 qtIcon.addFile(":/[email protected]");
321 }
322
323 void PixmapPainter::paintEvent(QPaintEvent *)
324 {
325 QPainter p(this);
326 p.fillRect(QRect(QPoint(0, 0), size()), QBrush(Qt::gray));
327
328 int pixmapPointSize = 32;
329 int y = 30;
330 int dy = 90;
331
332 int x = 10;
333 int dx = 40;
334 // draw at point
335 // qDebug() << "paint pixmap" << pixmap1X.devicePixelRatio();
336 p.drawPixmap(x, y, pixmap1X);
337 x+=dx;p.drawPixmap(x, y, pixmap2X);
338 x+=dx;p.drawPixmap(x, y, pixmapLarge);
339 x+=dx*2;p.drawPixmap(x, y, qtIcon.pixmap(QSize(pixmapPointSize, pixmapPointSize)));
340 x+=dx;p.drawImage(x, y, image1X);
341 x+=dx;p.drawImage(x, y, image2X);
342 x+=dx;p.drawImage(x, y, imageLarge);
343
344 // draw at 32x32 rect
345 y+=dy;
346 x = 10;
347 p.drawPixmap(QRect(x, y, pixmapPointSize, pixmapPointSize), pixmap1X);
348 x+=dx;p.drawPixmap(QRect(x, y, pixmapPointSize, pixmapPointSize), pixmap2X);
349 x+=dx;p.drawPixmap(QRect(x, y, pixmapPointSize, pixmapPointSize), pixmapLarge);
350 x+=dx;p.drawPixmap(QRect(x, y, pixmapPointSize, pixmapPointSize), qtIcon.pixmap(QSize(pixmapPointSize, pixmapPointSize)));
351 x+=dx;p.drawImage(QRect(x, y, pixmapPointSize, pixmapPointSize), image1X);
352 x+=dx;p.drawImage(QRect(x, y, pixmapPointSize, pixmapPointSize), image2X);
353 x+=dx;p.drawImage(QRect(x, y, pixmapPointSize, pixmapPointSize), imageLarge);
354
355
356 // draw at 64x64 rect
357 y+=dy - 50;
358 x = 10;
359 p.drawPixmap(QRect(x, y, pixmapPointSize * 2, pixmapPointSize * 2), pixmap1X);
360 x+=dx * 2; p.drawPixmap(QRect(x, y, pixmapPointSize * 2, pixmapPointSize * 2), pixmap2X);
361 x+=dx * 2; p.drawPixmap(QRect(x, y, pixmapPointSize * 2, pixmapPointSize * 2), pixmapLarge);
362 x+=dx * 2; p.drawPixmap(QRect(x, y, pixmapPointSize * 2, pixmapPointSize * 2), qtIcon.pixmap(QSize(pixmapPointSize, pixmapPointSize)));
363 x+=dx * 2; p.drawImage(QRect(x, y, pixmapPointSize * 2, pixmapPointSize * 2), image1X);
364 x+=dx * 2; p.drawImage(QRect(x, y, pixmapPointSize * 2, pixmapPointSize * 2), image2X);
365 x+=dx * 2; p.drawImage(QRect(x, y, pixmapPointSize * 2, pixmapPointSize * 2), imageLarge);
366 }
367
368 class TiledPixmapPainter : public QWidget
369 {
370 public:
371 TiledPixmapPainter();
372
373 void paintEvent(QPaintEvent *event) override;
374
375 private:
376 QPixmap pixmap1X;
377 QPixmap pixmap2X;
378 QPixmap pixmapLarge;
379 };
380
381 TiledPixmapPainter::TiledPixmapPainter()
382 {
383 pixmap1X = QPixmap(":/qticon32.png");
384 pixmap2X = QPixmap(":/[email protected]");
385 pixmapLarge = QPixmap(":/qticon64.png");
386 }
387
388 void TiledPixmapPainter::paintEvent(QPaintEvent *event)
389 {
390 Q_UNUSED(event);
391 QPainter p(this);
392
393 int xoff = 10;
394 int yoff = 10;
395 int tiles = 4;
396 int pixmapEdge = 32;
397 int tileAreaEdge = pixmapEdge * tiles;
398
399 // Expected behavior for both 1x and 2x dislays:
400 // 1x pixmap : 4 x 4 tiles
401 // large pixmap: 2 x 2 tiles
402 // 2x pixmap : 4 x 4 tiles
403 //
404 // On a 2x display the 2x pixmap tiles
405 // will be drawn in high resolution.
406 p.drawTiledPixmap(QRect(xoff, yoff, tileAreaEdge, tileAreaEdge), pixmap1X);
407 yoff += tiles * pixmapEdge + 10;
408 p.drawTiledPixmap(QRect(xoff, yoff, tileAreaEdge, tileAreaEdge), pixmapLarge);
409 yoff += tiles * pixmapEdge + 10;
410 p.drawTiledPixmap(QRect(xoff, yoff, tileAreaEdge, tileAreaEdge), pixmap2X);
411
412 // Again, with an offset. The offset is in
413 // device-independent pixels.
414 QPoint offset(40, 40); // larger than the pixmap edge size to exercise that code path
415 yoff = 10;
416 xoff = 20 + tiles * pixmapEdge ;
417 p.drawTiledPixmap(QRect(xoff, yoff, tileAreaEdge, tileAreaEdge), pixmap1X, offset);
418 yoff += tiles * pixmapEdge + 10;
419 p.drawTiledPixmap(QRect(xoff, yoff, tileAreaEdge, tileAreaEdge), pixmapLarge, offset);
420 yoff += tiles * pixmapEdge + 10;
421 p.drawTiledPixmap(QRect(xoff, yoff, tileAreaEdge, tileAreaEdge), pixmap2X, offset);
422 }
423
424 class Labels : public QWidget
425 {
426 public:
427 Labels();
428
429 private:
430 QPixmap pixmap1X;
431 QPixmap pixmap2X;
432 QPixmap pixmapLarge;
433 QIcon qtIcon;
434 };
435
436 Labels::Labels()
437 {
438 pixmap1X = QPixmap(":/qticon32.png");
439 pixmap2X = QPixmap(":/[email protected]");
440 pixmapLarge = QPixmap(":/qticon64.png");
441
442 qtIcon.addFile(":/qticon32.png");
443 qtIcon.addFile(":/[email protected]");
444 setWindowIcon(qtIcon);
445 setWindowTitle(formatWindowTitle("Labels"));
446
447 QLabel *label1x = new QLabel();
448 label1x->setPixmap(pixmap1X);
449 QLabel *label2x = new QLabel();
450 label2x->setPixmap(pixmap2X);
451 QLabel *labelIcon = new QLabel();
452 labelIcon->setPixmap(qtIcon.pixmap(QSize(32,32)));
453 QLabel *labelLarge = new QLabel();
454 labelLarge->setPixmap(pixmapLarge);
455
456 QHBoxLayout *layout = new QHBoxLayout(this);
457 layout->addWidget(label1x); //expected low-res on high-dpi displays
458 layout->addWidget(label2x); //expected high-res on high-dpi displays
459 layout->addWidget(labelIcon); //expected high-res on high-dpi displays
460 layout->addWidget(labelLarge); // expected large size and low-res
461 setLayout(layout);
462 }
463
464 class MainWindow : public QMainWindow
465 {
466 Q_OBJECT
467 public:
468 MainWindow();
469 QMenu *addNewMenu(const QString &title, int itemCount = 5);
470
471 private slots:
472 void maskActionToggled(bool t);
473
474 private:
475 QIcon qtIcon;
476 QIcon qtIcon1x;
477 QIcon qtIcon2x;
478
479 QToolBar *fileToolBar;
480 QAction *m_maskAction;
481 int menuCount = 0;
482 };
483
484 MainWindow::MainWindow()
485 {
486 // beware that QIcon auto-loads the @2x versions.
487 qtIcon1x.addFile(":/qticon16.png");
488 qtIcon2x.addFile(":/qticon32.png");
489 setWindowIcon(qtIcon);
490 setWindowTitle(formatWindowTitle("MainWindow"));
491
492 fileToolBar = addToolBar(tr("File"));
493 // fileToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
494 fileToolBar->addAction(new QAction(qtIcon1x, QString("1x"), this));
495 fileToolBar->addAction(new QAction(qtIcon2x, QString("2x"), this));
496 addNewMenu("&Edit");
497 addNewMenu("&Build");
498 addNewMenu("&Debug", 4);
499 QMenu *menu = addNewMenu("&Transmogrify", 7);
500 menu->addSeparator();
501 m_maskAction = menu->addAction("Mask");
502 m_maskAction->setCheckable(true);
503 connect(m_maskAction, &QAction::toggled, this, &MainWindow::maskActionToggled);
504 fileToolBar->addAction(m_maskAction);
505 addNewMenu("T&ools");
506 addNewMenu("&Help", 2);
507 }
508
509 QMenu *MainWindow::addNewMenu(const QString &title, int itemCount)
510 {
511 QMenu *menu = menuBar()->addMenu(title);
512 for (int i = 0; i < itemCount; i++) {
513 menuCount++;
514 QString s = "Menu item " + QString::number(menuCount);
515 if (i == 3) {
516 QMenu *subMenu = menu->addMenu(s);
517 for (int j = 1; j < 4; j++)
518 subMenu->addAction(QString::fromLatin1("SubMenu item %1.%2").arg(menuCount).arg(j));
519 } else {
520 menu->addAction(s);
521 }
522 }
523 return menu;
524 }
525
526 void MainWindow::maskActionToggled(bool t)
527 {
528 if (t) {
529 QList<QPoint> upperLeftTriangle;
530 upperLeftTriangle << QPoint(0, 0) << QPoint(width(), 0) << QPoint(0, height());
531 setMask(QRegion(QPolygon(upperLeftTriangle)));
532 } else {
533 clearMask();
534 }
535 }
536
537 class StandardIcons : public QWidget
538 {
539 public:
540 void paintEvent(QPaintEvent *) override
541 {
542 int x = 10;
543 int y = 10;
544 int dx = 50;
545 int dy = 50;
546 int maxX = 500;
547
548 for (uint iconIndex = QStyle::SP_TitleBarMenuButton; iconIndex < QStyle::SP_MediaVolumeMuted; ++iconIndex) {
549 QIcon icon = qApp->style()->standardIcon(QStyle::StandardPixmap(iconIndex));
550 QPainter p(this);
551 p.drawPixmap(x, y, icon.pixmap(dx - 5, dy - 5));
552 if (x + dx > maxX)
553 y+=dy;
554 x = ((x + dx) % maxX);
555 }
556 }
557 };
558
559 class Caching : public QWidget
560 {
561 public:
562 void paintEvent(QPaintEvent *) override
563 {
564 QSize layoutSize(75, 75);
565
566 QPainter widgetPainter(this);
567 widgetPainter.fillRect(QRect(QPoint(0, 0), this->size()), Qt::gray);
568
569 {
570 const qreal devicePixelRatio = this->windowHandle()->devicePixelRatio();
571 QPixmap cache(layoutSize * devicePixelRatio);
572 cache.setDevicePixelRatio(devicePixelRatio);
573
574 QPainter cachedPainter(&cache);
575 cachedPainter.fillRect(QRect(0,0, 75, 75), Qt::blue);
576 cachedPainter.fillRect(QRect(10,10, 55, 55), Qt::red);
577 cachedPainter.drawEllipse(QRect(10,10, 55, 55));
578
579 QPainter widgetPainter(this);
580 widgetPainter.drawPixmap(QPoint(10, 10), cache);
581 }
582
583 {
584 const qreal devicePixelRatio = this->windowHandle()->devicePixelRatio();
585 QImage cache = QImage(layoutSize * devicePixelRatio, QImage::Format_ARGB32_Premultiplied);
586 cache.setDevicePixelRatio(devicePixelRatio);
587
588 QPainter cachedPainter(&cache);
589 cachedPainter.fillRect(QRect(0,0, 75, 75), Qt::blue);
590 cachedPainter.fillRect(QRect(10,10, 55, 55), Qt::red);
591 cachedPainter.drawEllipse(QRect(10,10, 55, 55));
592
593 QPainter widgetPainter(this);
594 widgetPainter.drawImage(QPoint(95, 10), cache);
595 }
596
597 }
598 };
599
600 class Style : public QWidget
601 {
602 public:
603 Style()
604 {
605 row1 = new QHBoxLayout(this);
606
607 button = new QPushButton();
608 button->setText("Test Button");
609 row1->addWidget(button);
610
611 lineEdit = new QLineEdit();
612 lineEdit->setText("Test Lineedit");
613 row1->addWidget(lineEdit);
614
615 slider = new QSlider();
616 row1->addWidget(slider);
617
618 row1->addWidget(new QSpinBox);
619 row1->addWidget(new QScrollBar);
620
621 auto tab = new QTabBar();
622 tab->addTab("Foo");
623 tab->addTab("Bar");
624 row1->addWidget(tab);
625 }
626
627 private:
628 QPushButton *button;
629 QLineEdit *lineEdit;
630 QSlider *slider;
631 QHBoxLayout *row1;
632 };
633
634 class Fonts : public QWidget
635 {
636 public:
637 void paintEvent(QPaintEvent *) override
638 {
639 QPainter painter(this);
640
641 // Points
642 int y = 10;
643 for (int fontSize = 6; fontSize < 18; fontSize += 2) {
644 QFont font;
645 font.setPointSize(fontSize);
646 QString string = QString(QStringLiteral("This text is in point size %1")).arg(fontSize);
647 painter.setFont(font);
648 y += (painter.fontMetrics().lineSpacing());
649 painter.drawText(10, y, string);
650 }
651
652 // Pixels
653 y += painter.fontMetrics().lineSpacing();
654 for (int fontSize = 6; fontSize < 18; fontSize += 2) {
655 QFont font;
656 font.setPixelSize(fontSize);
657 QString string = QString(QStringLiteral("This text is in pixel size %1")).arg(fontSize);
658 painter.setFont(font);
659 y += (painter.fontMetrics().lineSpacing());
660 painter.drawText(10, y, string);
661 }
662 }
663 };
664
665
666 template <typename T>
667 void apiTestdevicePixelRatioGetter()
668 {
669 if (0) {
670 T *t = nullptr;
671 t->devicePixelRatio();
672 }
673 }
674
675 template <typename T>
676 void apiTestdevicePixelRatioSetter()
677 {
678 if (0) {
679 T *t = nullptr;
680 t->setDevicePixelRatio(2.0);
681 }
682 }
683
684 void apiTest()
685 {
686 // compile call to devicePixelRatio getter and setter (verify spelling)
687 apiTestdevicePixelRatioGetter<QWindow>();
688 apiTestdevicePixelRatioGetter<QScreen>();
689 apiTestdevicePixelRatioGetter<QGuiApplication>();
690
691 apiTestdevicePixelRatioGetter<QImage>();
692 apiTestdevicePixelRatioSetter<QImage>();
693 apiTestdevicePixelRatioGetter<QPixmap>();
694 apiTestdevicePixelRatioSetter<QPixmap>();
695 }
696
697 // Request and draw an icon at different sizes
698 class IconDrawing : public QWidget
699 {
700 public:
701 IconDrawing()
702 {
703 const QString tempPath = m_temporaryDir.path();
704 const QString path32 = tempPath + "/qticon32.png";
705 const QString path32_2 = tempPath + "/qticon32-2.png";
706 const QString path32_2x = tempPath + "/[email protected]";
707
708 QFile::copy(":/qticon32.png", path32_2);
709 QFile::copy(":/qticon32.png", path32);
710 QFile::copy(":/[email protected]", path32_2x);
711
712 iconHighDPI.reset(new QIcon(path32)); // will auto-load @2x version.
713 iconNormalDpi.reset(new QIcon(path32_2)); // does not have a 2x version.
714 }
715
716 void paintEvent(QPaintEvent *) override
717 {
718 int x = 10;
719 int y = 10;
720 int dx = 50;
721 int dy = 50;
722 int maxX = 600;
723 int minSize = 5;
724 int maxSize = 64;
725 int sizeIncrement = 5;
726
727 // normal icon
728 for (int size = minSize; size < maxSize; size += sizeIncrement) {
729 QPainter p(this);
730 p.drawPixmap(x, y, iconNormalDpi->pixmap(size, size));
731 if (x + dx > maxX)
732 y+=dy;
733 x = ((x + dx) % maxX);
734 }
735 x = 10;
736 y+=dy;
737
738 // high-dpi icon
739 for (int size = minSize; size < maxSize; size += sizeIncrement) {
740 QPainter p(this);
741 p.drawPixmap(x, y, iconHighDPI->pixmap(size, size));
742 if (x + dx > maxX)
743 y+=dy;
744 x = ((x + dx) % maxX);
745 }
746 }
747
748 private:
749 QTemporaryDir m_temporaryDir;
750 QScopedPointer<QIcon> iconHighDPI;
751 QScopedPointer<QIcon> iconNormalDpi;
752 };
753
754 // Icons on buttons
755 class Buttons : public QWidget
756 {
757 public:
758 Buttons()
759 {
760 QIcon icon;
761 icon.addFile(":/[email protected]");
762
763 QPushButton *button = new QPushButton(this);
764 button->setIcon(icon);
765 button->setText("16@2x");
766
767 QTabBar *tab = new QTabBar(this);
768 tab->addTab(QIcon(":/qticon16.png"), "16@1x");
769 tab->addTab(QIcon(":/[email protected]"), "16@2x");
770 tab->addTab(QIcon(":/qticon16.png"), "");
771 tab->addTab(QIcon(":/[email protected]"), "");
772 tab->move(10, 100);
773 tab->show();
774
775 auto toolBar = new QToolBar(this);
776 toolBar->addAction(QIcon(":/qticon16.png"), "16");
777 toolBar->addAction(QIcon(":/[email protected]"), "16@2x");
778 toolBar->addAction(QIcon(":/qticon32.png"), "32");
779 toolBar->addAction(QIcon(":/[email protected]"), "32@2x");
780
781 toolBar->move(10, 200);
782 toolBar->show();
783 }
784 };
785
786 class LinePainter : public QWidget
787 {
788 public:
789 void paintEvent(QPaintEvent *event) override;
790 void mousePressEvent(QMouseEvent *event) override;
791 void mouseReleaseEvent(QMouseEvent *event) override;
792 void mouseMoveEvent(QMouseEvent *event) override;
793
794 private:
795 QPoint lastMousePoint;
796 QList<QPoint> linePoints;
797 };
798
799 void LinePainter::paintEvent(QPaintEvent *)
800 {
801 QPainter p(this);
802 p.fillRect(QRect(QPoint(0, 0), size()), QBrush(Qt::gray));
803
804 // Default antialiased line
805 p.setRenderHint(QPainter::Antialiasing);
806 p.drawLines(linePoints);
807
808 // Cosmetic 1 antialiased line
809 QPen pen;
810 pen.setCosmetic(true);
811 pen.setWidth(1);
812 p.setPen(pen);
813 p.translate(3, 3);
814 p.drawLines(linePoints);
815
816 // Aliased cosmetic 1 line
817 p.setRenderHint(QPainter::Antialiasing, false);
818 p.translate(3, 3);
819 p.drawLines(linePoints);
820 }
821
822 void LinePainter::mousePressEvent(QMouseEvent *event)
823 {
824 lastMousePoint = event->pos();
825 }
826
827 void LinePainter::mouseReleaseEvent(QMouseEvent *)
828 {
829 lastMousePoint = QPoint();
830 }
831
832 void LinePainter::mouseMoveEvent(QMouseEvent *event)
833 {
834 if (lastMousePoint.isNull())
835 return;
836
837 QPoint newMousePoint = event->pos();
838 if (lastMousePoint == newMousePoint)
839 return;
840 linePoints.append(lastMousePoint);
841 linePoints.append(newMousePoint);
842 lastMousePoint = newMousePoint;
843 update();
844 }
845
846 class CursorTester : public QWidget
847 {
848 public:
849 CursorTester() = default;
850
851 inline QRect getRect(int idx) const
852 {
853 int h = height() / 2;
854 return QRect(10, 10 + h * (idx - 1), width() - 20, h - 20);
855 }
856
857 void paintEvent(QPaintEvent *) override
858 {
859 QPainter p(this);
860 QRect r1 = getRect(1);
861 QRect r2 = getRect(2);
862 p.fillRect(r1, QColor(200, 200, 250));
863 p.drawText(r1, "Drag from here to move a window based on QCursor::pos()");
864 p.fillRect(r2, QColor(250, 200, 200));
865 p.drawText(r2, "Drag from here to move a window based on mouse event position");
866
867 if (moving) {
868 p.setPen(Qt::darkGray);
869 QFont f = font();
870 f.setPointSize(8);
871 p.setFont(f);
872 p.drawEllipse(mousePos, 30,60);
873 QPoint pt = mousePos - QPoint(0, 60);
874 QPoint pt2 = pt - QPoint(30,10);
875 QPoint offs(30, 0);
876 p.drawLine(pt, pt2);
877 p.drawLine(pt2 - offs, pt2 + offs);
878 p.drawText(pt2 - offs, "mouse pos");
879
880 p.setPen(QColor(50,130,70));
881 QPoint cursorPos = mapFromGlobal(QCursor::pos());
882 pt = cursorPos - QPoint(0, 30);
883 pt2 = pt + QPoint(60, -20);
884 p.drawEllipse(cursorPos, 60, 30);
885 p.drawLine(pt, pt2);
886 p.drawLine(pt2 - offs, pt2 + offs);
887 p.drawText(pt2 - offs, "cursor pos");
888 }
889 }
890
891 void mousePressEvent(QMouseEvent *e) override
892 {
893 if (moving)
894 return;
895 QRect r1 = getRect(1);
896 QRect r2 = getRect(2);
897
898 moving = r1.contains(e->pos()) || r2.contains(e->pos());
899 if (!moving)
900 return;
901 useCursorPos = r1.contains(e->pos());
902
903 if (!moveLabel)
904 moveLabel = new QLabel(this,Qt::BypassWindowManagerHint|Qt::FramelessWindowHint|Qt::Window );
905
906 if (useCursorPos)
907 moveLabel->setText("I'm following QCursor::pos()");
908 else
909 moveLabel->setText("I'm following QMouseEvent::globalPos()");
910 moveLabel->adjustSize();
911 mouseMoveEvent(e);
912 moveLabel->show();
913 }
914
915 void mouseReleaseEvent(QMouseEvent *) override
916 {
917 if (moveLabel)
918 moveLabel->hide();
919 update();
920 moving = false;
921 }
922
923 void mouseMoveEvent(QMouseEvent *e) override
924 {
925 if (!moving)
926 return;
927 QPoint pos = useCursorPos ? QCursor::pos() : e->globalPosition().toPoint();
928 pos -= moveLabel->rect().center();
929 moveLabel->move(pos);
930 mousePos = e->pos();
931 update();
932 }
933
934 private:
935 QLabel *moveLabel = nullptr;
936 QPoint mousePos;
937 bool useCursorPos = false;
938 bool moving = false;
939 };
940
941 class ScreenDisplayer : public QWidget
942 {
943 public:
944 ScreenDisplayer() = default;
945
946 void timerEvent(QTimerEvent *) override
947 {
948 update();
949 }
950
951 void mousePressEvent(QMouseEvent *) override
952 {
953 if (!moveLabel)
954 moveLabel = new QLabel(this,Qt::BypassWindowManagerHint|Qt::FramelessWindowHint|Qt::Window );
955 moveLabel->setText("Hello, Qt this is a label\nwith some text");
956 moveLabel->show();
957 }
958
959 void mouseMoveEvent(QMouseEvent *e) override
960 {
961 if (!moveLabel)
962 return;
963 moveLabel->move(e->pos() / scaleFactor);
964 QString str;
965 QDebug dbg(&str);
966 dbg.setAutoInsertSpaces(false);
967 dbg << moveLabel->geometry();
968 moveLabel->setText(str);
969 }
970
971 void mouseReleaseEvent(QMouseEvent *) override
972 {
973 if (moveLabel)
974 moveLabel->hide();
975 }
976
977 void showEvent(QShowEvent *) override
978 {
979 refreshTimer.start(300, this);
980 }
981
982 void hideEvent(QHideEvent *) override
983 {
984 refreshTimer.stop();
985 }
986
987 void paintEvent(QPaintEvent *) override
988 {
989 QPainter p(this);
990 QRectF total;
991 const auto screens = QGuiApplication::screens();
992 for (const QScreen *screen : screens)
993 total |= screen->geometry();
994 if (total.isEmpty())
995 return;
996
997 scaleFactor = qMin(width()/total.width(), height()/total.height());
998
999 p.fillRect(rect(), Qt::black);
1000 p.scale(scaleFactor, scaleFactor);
1001 p.translate(-total.topLeft());
1002 p.setPen(QPen(Qt::white, 10));
1003 p.setBrush(Qt::gray);
1004
1005 for (const QScreen *screen : screens) {
1006 p.drawRect(screen->geometry());
1007 QFont f = font();
1008 f.setPixelSize(screen->geometry().height() / 8);
1009 p.setFont(f);
1010 p.drawText(screen->geometry(), Qt::AlignCenter, screen->name());
1011 }
1012 p.setBrush(QColor(200,220,255,127));
1013
1014 const auto topLevels = QApplication::topLevelWidgets();
1015 for (QWidget *widget : topLevels) {
1016 if (!widget->isHidden())
1017 p.drawRect(widget->geometry());
1018 }
1019
1020 QPolygon cursorShape;
1021 cursorShape << QPoint(0,0) << QPoint(20, 60)
1022 << QPoint(30, 50) << QPoint(60, 80)
1023 << QPoint(80, 60) << QPoint(50, 30)
1024 << QPoint(60, 20);
1025 cursorShape.translate(QCursor::pos());
1026 p.drawPolygon(cursorShape);
1027 }
1028
1029 private:
1030 QLabel *moveLabel = nullptr;
1031 qreal scaleFactor = 1;
1032 QBasicTimer refreshTimer;
1033 };
1034
1035 class PhysicalSizeTest : public QWidget
1036 {
1037 Q_OBJECT
1038 public:
1039 PhysicalSizeTest() = default;
1040
1041 void paintEvent(QPaintEvent *event) override;
1042
1043 void resizeEvent(QResizeEvent *) override
1044 {
1045 qreal ppi = window()->windowHandle()->screen()->physicalDotsPerInchX();
1046 QSizeF s = size();
1047 if (!m_ignoreResize)
1048 m_physicalSize = s / ppi;
1049 }
1050
1051 bool event(QEvent *event) override
1052 {
1053 if (event->type() == QEvent::ScreenChangeInternal) {
1054 // we will get resize events when the scale factor changes
1055 m_ignoreResize = true;
1056 QTimer::singleShot(100, this, &PhysicalSizeTest::handleScreenChange);
1057 }
1058 return QWidget::event(event);
1059 }
1060
1061 public slots:
1062 void handleScreenChange()
1063 {
1064 qreal ppi = window()->windowHandle()->screen()->physicalDotsPerInchX();
1065 QSizeF newSize = m_physicalSize * ppi;
1066 resize(newSize.toSize());
1067 m_ignoreResize = false;
1068 }
1069
1070 private:
1071 QSizeF m_physicalSize;
1072 bool m_ignoreResize = false;
1073 };
1074
1075 void PhysicalSizeTest::paintEvent(QPaintEvent *)
1076 {
1077 QPainter p(this);
1078 p.setRenderHint(QPainter::Antialiasing);
1079
1080 qreal ppi = window()->windowHandle()->screen()->physicalDotsPerInchX();
1081 qreal ppmm = ppi / 25.4;
1082 qreal h = 15 * ppmm;
1083 QRectF rulerRect(0,0, width(), h);
1084 rulerRect.moveCenter(rect().center());
1085
1086 QFont f = font();
1087 f.setPixelSize(18);
1088 p.setFont(f);
1089
1090 // draw a rectangle in (Qt) pixel coordinates, for comparison
1091 QRect pixelRect(0, 0, 300, 50);
1092 pixelRect.moveTopLeft(QPoint(5 * ppmm, rulerRect.bottom() + 5 * ppmm));
1093 p.fillRect(pixelRect, QColor(199,222,255));
1094 p.drawText(pixelRect, "This rectangle is 300x50 pixels");
1095
1096 f.setPixelSize(4 * ppmm);
1097 p.setFont(f);
1098
1099 QRectF topRect(0, 0, width(), rulerRect.top());
1100 p.drawText(topRect, Qt::AlignCenter, "The ruler is drawn in physical units.\nThis window tries to keep its physical size\nwhen moved between screens.");
1101
1102 // draw a ruler in real physical coordinates
1103
1104 p.fillRect(rulerRect, QColor(255, 222, 111));
1105
1106 QPen linePen(Qt::black, 0.3 * ppmm);
1107 p.setPen(linePen);
1108 f.setBold(true);
1109 p.setFont(f);
1110
1111 qreal vCenter = rulerRect.center().y();
1112 p.drawLine(0, vCenter, width(), vCenter);
1113
1114 // cm
1115 for (int i = 0;;) {
1116 i++;
1117 qreal x = i * ppmm;
1118 if (x > width())
1119 break;
1120 qreal y = rulerRect.bottom();
1121 qreal len;
1122 if (i % 5)
1123 len = 2 * ppmm;
1124 else if (i % 10)
1125 len = 3 * ppmm;
1126 else
1127 len = h / 2;
1128
1129 p.drawLine(QPointF(x, y), QPointF(x, y - len));
1130 if (i % 10 == 5) {
1131 QRectF textR(0, 0, 5 * ppmm, h / 2 - 2 * ppmm);
1132 textR.moveTopLeft(QPointF(x, vCenter));
1133 int n = i / 10 + 1;
1134 if (n % 10 == 0)
1135 p.setPen(Qt::red);
1136 p.drawText(textR, Qt::AlignCenter, QString::number(n));
1137 p.setPen(linePen);
1138 }
1139 }
1140
1141 //inches
1142 for (int i = 0;;) {
1143 i++;
1144 qreal x = i * ppi / 16;
1145 if (x > width())
1146 break;
1147 qreal y = rulerRect.top();
1148
1149 qreal d = h / 10;
1150 qreal len;
1151 if (i % 2)
1152 len = 1 * d;
1153 else if (i % 4)
1154 len = 2 * d;
1155 else if (i % 8)
1156 len = 3 * d;
1157 else if (i % 16)
1158 len = 4 * d;
1159 else
1160 len = h / 2;
1161
1162 p.drawLine(QPointF(x, y), QPointF(x, y + len));
1163 if (i % 16 == 12) {
1164 QRectF textR(0, 0, 0.25 * ppi, h / 2 - 2 * d);
1165 textR.moveBottomLeft(QPointF(x, vCenter));
1166 p.drawText(textR, Qt::AlignCenter, QString::number(1 + i/16));
1167 }
1168 }
1169
1170 }
1171
1172 class GraphicsViewCaching : public QGraphicsView
1173 {
1174 public:
1175 GraphicsViewCaching()
1176 {
1177 auto scene = new QGraphicsScene(0, 0, 400, 400);
1178
1179 QGraphicsTextItem *item = scene->addText("NoCache");
1180 item->setCacheMode(QGraphicsItem::NoCache);
1181 item->setPos(10, 10);
1182
1183 item = scene->addText("ItemCoordinateCache");
1184 item->setCacheMode(QGraphicsItem::ItemCoordinateCache);
1185 item->setPos(10, 30);
1186
1187 item = scene->addText("DeviceCoordinateCache");
1188 item->setCacheMode(QGraphicsItem::DeviceCoordinateCache);
1189 item->setPos(10, 50);
1190
1191 setScene(scene);
1192 }
1193 };
1194
1195 class MetricsTest : public QTabWidget
1196 {
1197 Q_OBJECT
1198 public:
1199 MetricsTest()
1200 {
1201 qDebug().noquote().nospace() << "MetricsTest " << QT_VERSION_STR
1202 << ' ' << QGuiApplication::platformName() << '\n'
1203 << R"(Relevant environment variables are:
1204 QT_FONT_DPI=N
1205 QT_SCALE_FACTOR=n
1206 QT_ENABLE_HIGHDPI_SCALING=0|1
1207 QT_USE_PHYSICAL_DPI=0|1
1208 QT_SCREEN_SCALE_FACTORS=N;N;N or QT_SCREEN_SCALE_FACTORS=name:N
1209 QT_SCALE_FACTOR_ROUNDING_POLICY=Round|Ceil|Floor|RoundPreferFloor|PassThrough
1210 QT_DPI_ADJUSTMENT_POLICY=AdjustDpi|DontAdjustDpi|AdjustUpOnly)";
1211
1212 m_textEdit = addTextPage("Parameters");
1213 m_logEdit = addTextPage("Screen Change Log");
1214
1215 const auto screens = QGuiApplication::screens();
1216 for (auto screen : screens)
1217 connectScreenChangeSignals(screen);
1218 connect(qApp, &QGuiApplication::screenAdded, this, &MetricsTest::slotScreenAdded);
1219 connect(qApp, &QGuiApplication::primaryScreenChanged, this, &MetricsTest::slotPrimaryScreenChanged);
1220 connect(qApp, &QGuiApplication::screenRemoved, this, &MetricsTest::slotScreenRemoved);
1221
1222 setWindowTitle(formatWindowTitle("Screens"));
1223 m_logTimer.start();
1224 logMessage(briefFormatScreens());
1225
1226 // Resize to roughly match the metrics text.
1227 const auto metrics = QFontMetrics(m_textEdit->font(), m_textEdit);
1228 const int width = 10 + metrics.horizontalAdvance(QStringLiteral("X")) * 50;
1229 const int height = 40 + metrics.height() * (10 + 8 * screens.size());
1230 resize(width, height);
1231 }
1232
1233 void setVisible(bool visible) override
1234 {
1235 QWidget::setVisible(visible);
1236 if (visible && !m_screenChangedConnected) {
1237 m_screenChangedConnected = true;
1238 QObject::connect(windowHandle(), &QWindow::screenChanged,
1239 this, &MetricsTest::screenChanged);
1240 updateMetrics();
1241 }
1242 }
1243
1244 void updateMetrics()
1245 {
1246 QString text;
1247 QTextStream str(&text);
1248
1249 auto currentScreen = windowHandle()->screen();
1250 const auto screens = QGuiApplication::screens();
1251 for (int i = 0, size = screens.size(); i < size; ++i) {
1252 auto screen = screens.at(i);
1253 auto platformScreen = screen->handle();
1254 str << "Screen #" << i << " \"" << screen->name() << '"';
1255 if (screen == currentScreen)
1256 str << " [current]";
1257 if (screen == QGuiApplication::primaryScreen())
1258 str << " [primary]";
1259 str << "\n screen geometry: " << screen->geometry()
1260 << "\n platform screen geometry: " << platformScreen->geometry()
1261 << "\n platform screen logicalDpi: " << platformScreen->logicalDpi().first;
1262
1263 #ifdef HAVE_SCREEN_BASE_DPI
1264 str << "\n platform screen logicalBaseDpi: " << platformScreen->logicalBaseDpi().first;
1265 #endif
1266 str << "\n platform screen devicePixelRatio: " <<platformScreen->devicePixelRatio()
1267 << "\n platform screen physicalDpi: " << screen->physicalDotsPerInch()
1268 << "\n\n";
1269 }
1270
1271 str << "widget devicePixelRatio: " << this->devicePixelRatio()
1272 << "\nwidget logicalDpi: " << this->logicalDpiX()
1273 << "\n\nQT_FONT_DPI: " << qgetenv("QT_FONT_DPI")
1274 << "\nQT_SCALE_FACTOR: " << qgetenv("QT_SCALE_FACTOR")
1275 << "\nQT_ENABLE_HIGHDPI_SCALING: " << qgetenv("QT_ENABLE_HIGHDPI_SCALING")
1276 << "\nQT_SCREEN_SCALE_FACTORS: " << qgetenv("QT_SCREEN_SCALE_FACTORS")
1277 << "\nQT_USE_PHYSICAL_DPI: " << qgetenv("QT_USE_PHYSICAL_DPI")
1278 << "\nQT_SCALE_FACTOR_ROUNDING_POLICY: " << qgetenv("QT_SCALE_FACTOR_ROUNDING_POLICY")
1279 << "\nQT_DPI_ADJUSTMENT_POLICY: " << qgetenv("QT_DPI_ADJUSTMENT_POLICY")
1280 << '\n';
1281
1282 m_textEdit->setPlainText(text);
1283 }
1284
1285 private slots:
1286 void screenChanged()
1287 {
1288 const QString message = QLatin1String("screenChanged ") + windowHandle()->screen()->name();
1289 qInfo("%s", qPrintable(message));
1290 logMessage(message);
1291 updateMetrics();
1292 }
1293
1294 void slotScreenAdded(QScreen *);
1295 void slotScreenRemoved(QScreen *);
1296 void slotPrimaryScreenChanged(QScreen *);
1297 void slotScreenGeometryChanged(const QRect &geometry)
1298 { logScreenChangeSignal(sender(), "geometry", geometry); }
1299 void slotScreenAvailableGeometryChanged(const QRect &geometry)
1300 { logScreenChangeSignal(sender(), "availableGeometry", geometry); }
1301 void slotScreenPhysicalSizeChanged(const QSizeF &size)
1302 { logScreenChangeSignal(sender(), "physicalSize", size); }
1303 void slotScreenPhysicalDotsPerInchChanged(qreal dpi)
1304 { logScreenChangeSignal(sender(), "physicalDotsPerInch", dpi); }
1305 void slotScreenLogicalDotsPerInchChanged(qreal dpi)
1306 { logScreenChangeSignal(sender(), "logicalDotsPerInch", dpi); }
1307 void slotScreenVirtualGeometryChanged(const QRect &rect)
1308 { logScreenChangeSignal(sender(), "virtualGeometry", rect); }
1309 void slotScreenPrimaryOrientationChanged(Qt::ScreenOrientation orientation)
1310 { logScreenChangeSignal(sender(), "primaryOrientation", orientation); }
1311 void slotScreenOrientationChanged(Qt::ScreenOrientation orientation)
1312 { logScreenChangeSignal(sender(), "orientation", orientation); }
1313 void slotScreenRefreshRateChanged(qreal refreshRate)
1314 { logScreenChangeSignal(sender(), "refreshRate", refreshRate); }
1315
1316 private:
1317 QPlainTextEdit *addTextPage(const QString &title);
1318 void logMessage(const QString &);
1319 void connectScreenChangeSignals(QScreen *s);
1320 static QString briefFormatScreens();
1321 template <class T>
1322 void logScreenChangeSignal(const QObject *o, const char *name, const T &value);
1323
1324 QPlainTextEdit *m_textEdit;
1325 QPlainTextEdit *m_logEdit;
1326 QElapsedTimer m_logTimer;
1327 bool m_screenChangedConnected = false;
1328 };
1329
1330 void MetricsTest::slotScreenAdded(QScreen *screen)
1331 {
1332 logMessage(QLatin1String("Added ") + screen->name() + QLatin1Char(' ')
1333 + briefFormatScreens());
1334 connectScreenChangeSignals(screen);
1335 }
1336
1337 void MetricsTest::slotScreenRemoved(QScreen *screen)
1338 {
1339 logMessage(QLatin1String("Removed ") + screen->name() + QLatin1Char(' ')
1340 + briefFormatScreens());
1341 }
1342
1343 void MetricsTest::slotPrimaryScreenChanged(QScreen *screen)
1344 {
1345 logMessage(QLatin1String("PrimaryScreenChanged ") + screen->name() + QLatin1Char(' ')
1346 + briefFormatScreens());
1347 }
1348
1349 QPlainTextEdit *MetricsTest::addTextPage(const QString &title)
1350 {
1351 auto result = new QPlainTextEdit(this);
1352 result->setReadOnly(true);
1353 result->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
1354 addTab(result, title);
1355 return result;
1356 }
1357
1358 void MetricsTest::logMessage(const QString &m)
1359 {
1360 const QString timeStamp =
1361 QStringLiteral("%1ms: %2").arg(m_logTimer.elapsed(), 6, 10, QLatin1Char('0')).arg(m);
1362 m_logEdit->appendPlainText(timeStamp);
1363 }
1364
1365 void MetricsTest::connectScreenChangeSignals(QScreen *s)
1366 {
1367 connect(s, &QScreen::geometryChanged, this, &MetricsTest::slotScreenGeometryChanged);
1368 connect(s, &QScreen::availableGeometryChanged, this, &MetricsTest::slotScreenAvailableGeometryChanged);
1369 connect(s, &QScreen::physicalSizeChanged, this, &MetricsTest::slotScreenPhysicalSizeChanged);
1370 connect(s, &QScreen::physicalDotsPerInchChanged, this, &MetricsTest::slotScreenPhysicalDotsPerInchChanged);
1371 connect(s, &QScreen::logicalDotsPerInchChanged, this, &MetricsTest::slotScreenLogicalDotsPerInchChanged);
1372 connect(s, &QScreen::virtualGeometryChanged, this, &MetricsTest::slotScreenVirtualGeometryChanged);
1373 connect(s, &QScreen::primaryOrientationChanged, this, &MetricsTest::slotScreenPrimaryOrientationChanged);
1374 connect(s, &QScreen::orientationChanged, this, &MetricsTest::slotScreenOrientationChanged);
1375 connect(s, &QScreen::refreshRateChanged, this, &MetricsTest::slotScreenRefreshRateChanged);
1376 }
1377
1378 QString MetricsTest::briefFormatScreens()
1379 {
1380 QString message;
1381 QTextStream str(&message);
1382 const auto screens = QGuiApplication::screens();
1383 for (int i = 0, size = screens.size(); i < size; ++i) {
1384 str << (i ? ", " : "(");
1385 str << screens.at(i)->name() << " " << screens.at(i)->geometry();
1386 }
1387 str << ')';
1388 return message;
1389 }
1390
1391 template <class T>
1392 void MetricsTest::logScreenChangeSignal(const QObject *o, const char *name, const T &value)
1393 {
1394 auto screen = qobject_cast<const QScreen *>(o);
1395 QString message;
1396 QTextStream(&message) << (screen ? screen->name() : QString()) << ' ' << name << " changed: " << value;
1397 logMessage(message);
1398 }
1399
1400 int main(int argc, char **argv)
1401 {
1402 qInfo("High DPI tester %s", QT_VERSION_STR);
1403
1404 QApplication app(argc, argv);
1405 QCoreApplication::setApplicationVersion(QT_VERSION_STR);
1406
1407 QCommandLineParser parser;
1408 parser.setApplicationDescription("High DPI tester. Pass one or more of the options to\n"
1409 "test various high-dpi aspects. \n"
1410 "--interactive is a special option and opens a configuration"
1411 " window.");
1412 parser.addHelpOption();
1413 parser.addVersionOption();
1414 QCommandLineOption controllerOption("interactive", "Show configuration window.");
1415 parser.addOption(controllerOption);
1416
1417 DemoContainerList demoList;
1418 demoList << new DemoContainer<PixmapPainter>("pixmap", "Test pixmap painter");
1419 demoList << new DemoContainer<TiledPixmapPainter>("tiledpixmap", "Test tiled pixmap painter");
1420 demoList << new DemoContainer<Labels>("label", "Test Labels");
1421 demoList << new DemoContainer<MainWindow>("mainwindow", "Test QMainWindow");
1422 demoList << new DemoContainer<StandardIcons>("standard-icons", "Test standard icons");
1423 demoList << new DemoContainer<Caching>("caching", "Test caching");
1424 demoList << new DemoContainer<Style>("styles", "Test style");
1425 demoList << new DemoContainer<Fonts>("fonts", "Test fonts");
1426 demoList << new DemoContainer<IconDrawing>("icondrawing", "Test icon drawing");
1427 demoList << new DemoContainer<Buttons>("buttons", "Test buttons");
1428 demoList << new DemoContainer<LinePainter>("linepainter", "Test line painting");
1429 demoList << new DemoContainer<DragWidget>("draganddrop", "Test drag and drop");
1430 demoList << new DemoContainer<CursorTester>("cursorpos", "Test cursor and window positioning");
1431 demoList << new DemoContainer<ScreenDisplayer>("screens", "Test screen and window positioning");
1432 demoList << new DemoContainer<PhysicalSizeTest>("physicalsize", "Test manual highdpi support using physicalDotsPerInch");
1433 demoList << new DemoContainer<GraphicsViewCaching>("graphicsview", "Test QGraphicsView caching");
1434 demoList << new DemoContainer<MetricsTest>("metrics", "Show screen metrics");
1435
1436 for (DemoContainerBase *demo : std::as_const(demoList))
1437 parser.addOption(demo->option());
1438
1439 parser.process(app);
1440
1441 //controller takes ownership of all demos
1442 DemoController controller(demoList, &parser);
1443
1444 if (parser.isSet(controllerOption) || (QCoreApplication::arguments().count()) <= 1)
1445 controller.show();
1446
1447 if (QApplication::topLevelWidgets().isEmpty())
1448 parser.showHelp(0);
1449
1450 return app.exec();
1451 }
1452
1453 #include "main.moc"