How can I add a QActionGroup to a toolbar with C++ (ie. without using Qt Designer)?
Printable View
How can I add a QActionGroup to a toolbar with C++ (ie. without using Qt Designer)?
I think this (link) 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.
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.
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...
Code:
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.
Simply pass the actiongroup as the parent argument when you create an action.Quote:
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.
The point is that adding the actiongroup would require less code than adding actions individually.Quote:
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.
Code:
toolbar->addActions(actionGroup->actions());
That is what I was looking for; thank you.
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.