Non interactive items in QMenu

From the QMenu documentation:

There are four kinds of action items: separators, actions that show a submenu, widgets, and actions that perform an action. Separators are inserted with addSeparator(), submenus with addMenu(), and all other items are considered action items.

This rings a bell: Widgets! You can add a widget to the menu? That means you are settled, you can do whatever you want.

What you need is a QWidgetAction object. It allows you to insert a custom widget as an action. Your titles will be custom widgets. If you only need a title, a QLabel should suffice:

QMenu* myMenu = new QMenu(...);
QLabel* label = new QLabel(tr("<b>Title</b>"), this);
label->setAlignment(Qt::AlignCenter);

QWidgetAction* a = new QWidgetAction(myMenu);
a->setDefaultWidget(label);

-- Source for this code

See this related question for more sophisticated example code: Is there a way to add a Widget to a QMenu in QtCreator


For Qt 5.1 and up, you should be using addSection(const QString &). It's designed precisely for what you're trying to do. The widget-based solutions will look weird unless you take great care at matching the fonts and spacing etc.

For Qt 4, you should use addAction(const QString &) as a fallback, if you really intend your code to compile with Qt 4. It's a reasonable tradeoff, I think.

For Qt 5.0 - well, you shouldn't be using it at all anymore, it's as simple as that :)

Tags:

C++

Qt

Qmenu