PDA

View Full Version : add actiongroup to toolbar



ravas
22nd July 2015, 00:22
How can I add a QActionGroup to a toolbar with C++ (ie. without using Qt Designer)?

mikag
22nd July 2015, 05:58
I think this (link) (http://www.qtcentre.org/threads/4501-Add-exclusive-buttons-in-a-toolbar-with-qtdesigner?p=23727#post23727) is what your looking for. Searching the forums for you there, but I were wondering why it wasn't possible to do it in the designer.

ravas
22nd July 2015, 06:09
I see code that adds actions to an actiongroup.
I don't see anything about adding the actiongroup to a toolbar.

I don't need to do this at all; I'm curious.

mikag
22nd July 2015, 06:47
But that's because you don't really need any more code. The docs do say you usually should create a QActionGroup and set it as the parent when creating the QActions belonging to it. But I've yet to see any code sample for that. Not that I've been looking for one.
All you do is add a few actions to a toolbar or menu and then create a group and add the relevant actions to it. Nothing else is needed. The group it self is newer added to anything, but setting the window as an owner will assure proper cleanup.

Edit: Now I did find a sample looking for something entirely different...


actionGroup = new QActionGroup(this);
a1 = actionGroup->addAction("a1");
a2 = actionGroup->addAction("a2");
...
toolbar->addActions(actionGroup->actions());

Still doesn't add the action group itself to the toolbar only the actions it owns.

ravas
22nd July 2015, 18:15
The docs do say you usually should create a QActionGroup and set it as the parent when creating the QActions belonging to it. But I've yet to see any code sample for that.

Simply pass the actiongroup as the parent argument when you create an action.


new QAction(tr("&Some Action"), action_group);


All you do is add a few actions to a toolbar or menu and then create a group and add the relevant actions to it. Nothing else is needed.

The point is that adding the actiongroup would require less code than adding actions individually.


toolbar->addActions(actionGroup->actions());

That is what I was looking for; thank you.

d_stranz
23rd July 2015, 17:48
The more useful thing about a QActionGroup is that you can enable / disable the group, which enables / disables all actions in it (and the toolbar / menu items to which the actions are attached). This is more efficient and less error-prone that having to control actions individually based on some state of your program.