How to add an entry to toolbar context menu in qt?
默认情况下,工具栏的上下文菜单填充有工具栏的名称。 我想通过附加条目扩展此上下文菜单。
我找到了一个扩展QTextEdit元素的上下文菜单的示例。
http://www.qtcentre.org/threads/35166-extend-the-standard-context-menu-of-qtextedit
但是,它使用QTextEdit类的createStandardContextMenu。 但是QToolBar似乎没有该属性:
http://doc.qt.io/qt-4.8/qtoolbar.html
编辑
显然,默认的上下文菜单是QMainWindow中的菜单。
http://doc.qt.io/qt-4.8/qmainwindow.html#createPopupMenu
不幸的是,我还不知道如何添加条目。
编辑
我正在使用此来源:
http://doc.qt.io/qt-5/qtwidgets-mainwindows-application-example.html
如果要为主窗口中的所有
1 2 3 4 5 6 7 8 9 | QMenu* MainWindow::createPopupMenu(){ //call the overridden method to get the default menu containing checkable entries //for the toolbars and dock widgets present in the main window QMenu* menu= QMainWindow::createPopupMenu(); //you can add whatever you want to the menu before returning it menu->addSeparator(); menu->addAction(tr("Custom Action"), this, SLOT(CustomActionSlot())); return menu; } |
您需要从
qmytoolbar.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #ifndef QMYTOOLBAR_H #define QMYTOOLBAR_H #include <QToolBar> class QMyToolBar : public QToolBar { Q_OBJECT public: explicit QMyToolBar(QWidget *parent = 0) : QToolBar(parent){} protected: void contextMenuEvent(QContextMenuEvent *event); }; #endif // QMYTOOLBAR_H |
qmytoolbar.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include"qmytoolbar.h" #include <QMenu> #include <QContextMenuEvent> void QMyToolBar::contextMenuEvent(QContextMenuEvent *event) { // QToolBar::contextMenuEvent(event); QMenu *menu = new QMenu(this); menu->addAction(tr("My Menu Item")); menu->exec(event->globalPos()); delete menu; } |
如果要保留标准菜单,请在我的主窗口中创建并添加项目,并保持指向
1 2 3 4 5 6 7 8 9 10 11 12 13 | void QMyToolBar::contextMenuEvent(QContextMenuEvent *event) { // QToolBar::contextMenuEvent(event); QMenu *menu = //new QMenu(this); m_pMainWindow->createPopupMenu(); menu->addAction(tr("My Menu Item")); menu->exec(event->globalPos()); delete menu; } |