Daniel
Daniel

Reputation: 3691

How to add an entry to toolbar context menu in qt?

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

Upvotes: 2

Views: 2736

Answers (2)

Mike
Mike

Reputation: 8355

No need to derive QToolBar if you want to provide the same context menu for all the QToolBars 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;
}

Upvotes: 5

mvidelgauz
mvidelgauz

Reputation: 2214

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;
}

Upvotes: 3

Related Questions