Jump to content

Qt for HarmonyOS/qtohosextras doc/Screen Display ID Example - main.cpp

From Qt Wiki
Revision as of 06:37, 17 September 2026 by Shawn Luo (talk | contribs) (Drop manual breadcrumb, MediaWiki renders it automatically (QTFOROH-2307))
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Screen Display ID Example - main.cpp

 // Copyright (C) 2025 The Qt Company Ltd.
 // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

 #include <QApplication>
 #include <QLabel>
 #include <QPushButton>
 #include <QScreen>
 #include <QVBoxLayout>
 #include <QWidget>
 #include <QtOhosExtras>

 namespace {

 void updateDisplayId(QWidget *window, QLabel *label)
 {
     auto displayId = QtOhosExtras::tryGetScreenDisplayId(window->windowHandle()->screen());
     label->setText(
         QStringLiteral("Display ID: %1")
             .arg(displayId
                 ? QString::number(*displayId)
                 : QLatin1String("<invalid>")));
 }

 QPushButton *createCheckDisplayButton(QWidget *window, QLabel *displayLabel)
 {
     auto *button = new QPushButton(QLatin1String("Check display ID"), window);
     QObject::connect(
         button, &QPushButton::clicked, window,
         [window, displayLabel]() {
             updateDisplayId(window, displayLabel);
         });
     return button;
 }

 }

 int main(int argc, char *argv[])
 {
     QApplication app(argc, argv);

     QWidget window;

     auto *instructionLabel = new QLabel(QLatin1String("Move window between the displays"), &window);
     auto *displayLabel = new QLabel(&window);
     auto *checkDisplayButton = createCheckDisplayButton(&window, displayLabel);

     auto *layout = new QVBoxLayout(&window);
     layout->addWidget(displayLabel);
     layout->addWidget(instructionLabel);
     layout->addWidget(checkDisplayButton);

     window.setLayout(layout);
     window.resize(400, 200);
     window.setWindowTitle(QLatin1String("Display ID Test"));
     window.show();

     updateDisplayId(&window, displayLabel);

     return app.exec();
 }