Structure for registering commands to the FreeCAD system.
Structure for registering commands to the FreeCAD system.
In GUI applications many commands can be invoked via a menu item, a toolbar button or an accelerator key. The answer of Qt to master this challenge is the class QAction. A QAction object can be added to a popup menu or a toolbar and keep the state of the menu item and the toolbar button synchronized.
For example, if the user clicks the menu item of a toggle action then the toolbar button gets also pressed and vice versa. For more details refer to your Qt documentation.
Since QAction inherits QObject and emits the triggered() signal or toggled() signal for toggle actions it is very convenient to connect these signals e.g. with slots of your MainWindow class. But this means that for every action an appropriate slot of MainWindow is necessary and leads to an inflated MainWindow class. Furthermore, it's simply impossible to provide plugins that may also need special slots – without changing the MainWindow class.
To solve these problems we have introduced the command framework to decouple QAction and MainWindow. The base classes of the framework are Gui::CommandBase and Gui::Action that represent the link between Qt's QAction world and the FreeCAD's command world.
The Action class holds a pointer to QAction and CommandBase and acts as a mediator and – to save memory – that gets created (Gui::CommandBase::createAction()) not before it is added (Gui::Command::addTo()) to a menu or toolbar.
Now, the implementation of the slots of MainWindow can be done in the method activated() of subclasses of Command instead.
For example, the implementation of the "Open file" command can be done as follows.
An instance of OpenCommand must be created and added to the Gui::CommandManager to make the class known to FreeCAD. To see how menus and toolbars can be built go to the Workbench Framework.