我的 qml 小部件中需要 ContextMenu。我有一个解决方案:创建QGraphicsProxyWidget,其中包含QMenu,但是有一个问题:上下文菜单在主窗口之外是不可见的。如何将主窗口设置为菜单的父级?自定义组件是个坏主意 - 我需要 QMenu 的可能性:执行、操作、弹出窗口等。
主.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();
}
}
}
主文件
#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();
}