ctinka
ctinka

Reputation: 413

How to add context menu to qml QDeclarativeView?

I need ContextMenu in my qml widgets. I have a solution: create QGraphicsProxyWidget, which contain QMenu, but there is a problem: the context menu is not visible outside the main window. How to set main window as parent of menu? Custom components is a bad idea - I need possibilities of the QMenu: exec, actions, pop-up and other.

Main.qml

import QtQuick 1.1
import CustomComponents 1.0

Rectangle {
    width: 360
    height: 360
    QMLContextMenu {
        id: menu
    }

    Text {
        text: qsTr("Hello World")
        anchors.centerIn: parent
    }
    MouseArea {
        anchors.fill: parent
        acceptedButtons: Qt.RightButton | Qt.LeftButton
        onClicked: {
            if(mouse.button === Qt.RightButton)
                menu.exec(mouse.x, mouse.y);
            else
                Qt.quit();
        }
    }
}

main.cpp

#include <QApplication>
#include "qmlapplicationviewer.h"
#include <QtCore>
#include <QtDeclarative>
#include <QtGui>

class QMLContextMenu : public QGraphicsProxyWidget
{
    Q_OBJECT
public:
    QMLContextMenu(QGraphicsItem* parent = 0) : QGraphicsProxyWidget(parent)
    {
        menuWidget = new QMenu("my menu");
        setWidget(menuWidget);
    }
public slots:
    QString exec(int x, int y)
    {
        menuWidget->clear();
        menuWidget->addAction("hello world!");
        menuWidget->addSeparator();
        menuWidget->addAction("or not...");
        //menuWidget->show();
        QAction *pResultAction = menuWidget->exec(QPoint(x, y));
        QString text;
        if(pResultAction)
            text = pResultAction->text();
        return text;
    }
private:
    QMenu *menuWidget;
}; 

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QScopedPointer<QApplication> app(createApplication(argc, argv));
    qmlRegisterType<QMLContextMenu>("CustomComponents", 1, 0, "QMLContextMenu");
    QmlApplicationViewer viewer;
    viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
    viewer.setMainQmlFile(QLatin1String("qml/quick1/main.qml"));
    viewer.showExpanded();
    return app->exec();
}

Upvotes: 1

Views: 1447

Answers (1)

Magog
Magog

Reputation: 505

Create you own rectangle with listview. But in this way there are lots of problems because in qml 1 qml widgets can't be top-level windows. I did that:

  1. Create separate ContextMenu.qml
  2. Use loader to instantiate it
  3. show it when I need it

Upvotes: 1

Related Questions