Jump to content

Qt for HarmonyOS/qtohosextras doc/Context Menu on Long Press Example - main.cpp

From Qt Wiki

Context Menu on Long Press 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 <QContextMenuEvent>
 #include <QDebug>
 #include <QMainWindow>
 #include <QMenu>
 #include <QPushButton>
 #include <QtOhosExtras>

 namespace {

 class MyButton : public QPushButton
 {
 public:
     using QPushButton::QPushButton;

 protected:
     void contextMenuEvent(QContextMenuEvent *event) override
     {
         QString reasonStr;

         switch (event->reason()) {
         case QContextMenuEvent::Mouse:
             reasonStr = "Mouse";
             break;
         case QContextMenuEvent::Keyboard:
             reasonStr = "Keyboard";
             break;
         case QContextMenuEvent::Other:
             reasonStr = "Other";
             break;
         default:
             reasonStr = QString("Unknown (%1)").arg(event->reason());
         }

         qDebug() << "Context menu event reason:" << reasonStr;
     }
 };

 }

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

     QtOhosExtras::QOhosAppContext::instance()->enableContextMenuEventOnLongPress();

     QMainWindow window;
     auto *button = new MyButton("Long-press me", &window);
     button->setGeometry(50, 50, 200, 50);
     window.setCentralWidget(button);
     window.resize(300, 150);
     window.show();

     return app.exec();
 }