Qt Support #28 – Creating a toolbar widget that is displayed with the context menu
You have probably seen applications that have a toolbar shown with a context menu. The toolbar enables the fast use of selected set of actions. Let’s take a look how you can create such a toolbar widget with Qt.
As the toolbar widget will be connected to the context menu of the application you will naturally need one. We won’t cover here the details of creating the context menu; instead you can take a look at the Menu Example (http://qt-project.org/doc/qt-4.8/mainwindows-menus.html) to see how one can be implemented. The example is also something you can use as basis when creating the toolbar functionality with the steps explained here.
First of all we need to create a widget for the toolbar. The toolbar widget can be inherited from QWidget and we need to make sure the Qt::Popup window flag is set for the widget. Also the position of the toolbar widget is something we want to change so that it’s placed on top of the context menu. This is why the position of the context menu is passed to the constructor of the toolbar widget.
ToolBarWidget::ToolBarWidget(QPoint pos, QWidget *parent) : QWidget(parent)
setWindowFlags(windowFlags() | Qt::Popup);
int newYPos = pos.y() - 50;
We need to select the actions that we want to enable via the toolbar widget and add them to the layout of the widget. For our toolbar widget we will have a combobox and two tool buttons:
QHBoxLayout *layout = new QHBoxLayout;
QComboBox *combo = new QComboBox(this);
QSize iconSize(20, 20);
QToolButton *openButton = new QToolButton;
connect(openButton, SIGNAL(clicked()), this, SLOT(open()));
QToolButton *quitButton = new QToolButton;
connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit()));
Now that the toolbar widget is in place all we need to do is to show the widget whenever the context menu is shown. This can be achieved by utilizing the contextMenuEvent() method. We create the widget, make the signal-slot connections needed and show the widget with the context menu.
void MainWindow::contextMenuEvent(QContextMenuEvent *event)
toolBarWidget = new ToolBarWidget(event->globalPos());
connect(&menu, SIGNAL(triggered(QAction*)), toolBarWidget, SLOT(close()));
And that gives us a context menu with a toolbar widget.
Now it’s your turn to try out, hopefully this will help you create even fancier menus. Should you have any questions related to this then if you are a customer you can always contact the Qt Support team via the Qt Support portal http://qt.digia.com/customerportal. Happy coding!
Update, You can get the source code for the example here: http://bit.ly/QWy79A
Subscribe to our newsletter
Try Qt 6.6 Now!
Download the latest release here: www.qt.io/download.
Qt 6.6. is a feature release with focus on improving UX capabilities including responsive UI technology and the Qt Graph module.
Check out all our open positions here and follow us on Instagram to see what it's like to be #QtPeople.