Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

c++ - Non interactive items in QMenu

I'm trying to build a menu with some items that are not interactive in QT. I subclass QMenu in my MyCustomMenuClass. I'm trying to add section titles to my menu so that it's clearer for the user.

For example, it should look like this:

My section 1 title
Action 1
Action 2
Action 3
My second section title
Action 4
Action 5

The issue is that the section titles always react to the mouse, but I would like them to not react to a mouse over so that it would be prettier. Any idea on how to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...