可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
By default the context menu of a toolbar is filled with the names of the toolbars. I would like to extend this context menu by an additional entry.
I found an example extending the context menu of a QTextEdit element.
http://www.qtcentre.org/threads/35166-extend-the-standard-context-menu-of-qtextedit
However, it uses the createStandardContextMenu of the QTextEdit class. But QToolBar appears not to have that property:
http://doc.qt.io/qt-4.8/qtoolbar.html
Edit
Apparently, the default context menu is the one from the QMainWindow.
http://doc.qt.io/qt-4.8/qmainwindow.html#createPopupMenu
Unfortunately, I have no clue yet how to add an entry to it.
Edit
I am working with this source:
http://doc.qt.io/qt-5/qtwidgets-mainwindows-application-example.html
回答1:
No need to derive QToolBar
if you want to provide the same context menu for all the QToolBar
s in your main window, you just need to override createPopupMenu()
in your main window to add your Custom Action to the returned menu like this:
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; }
回答2:
You need to derive your own class from QToolBar
and override its virtual function contextMenuEvent
:
qmytoolbar.h
#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
#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; }
If you want to retain standard menu created my main window and add your items to it keep a pointer to your QMainWindow' in your QMyToolBar and modify 'QMyToolBar::contextMenuEvent
:
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; }