Saturday, December 29, 2007

Adding a menu to KMainWindow programmatically

First of all, let me stress that I'm not an experienced KDE programmer: my only KDE application, for now, is SourceHighlightIDE, a sort of IDE for developing GNU Source-highlight language definition files. While I was adding new features to this program, for the next release, I wanted to add the typical "Window" menu that permits tile all the windows in the workspace or cascade them, or selecting a specific window (SourceHighlightIDE is a MDI application). I then simply added this code to the KMainWindow subclass:


windowsMenu = new KPopupMenu( this );
connect( windowsMenu, SIGNAL( aboutToShow() ),
this, SLOT( windowsMenuAboutToShow() ) );
menuBar()->activateItemAt(-1); //needed as insertItem might crash if a menu is activated

// position: 2, means the third menu (the fourth one is Help)
menuBar()->insertItem( "&Window", windowsMenu, -1, 2);

However, the "Window" menu was never added to the application.

Actually, I know that one should add additional menus to the .rc file, e.g.,
<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
<kpartgui name="sourcehighlightide" version="1">
<MenuBar>
<Menu name="custom"><text>C&amp;ustom</text>
<Action name="custom_action" />
</Menu>
</MenuBar>
</kpartgui>

but I wanted a way to add the menu programmaticaly, so that I would not depend on the .rc file that must be installed.

Actually, the code added by me above works, but you must make sure to execute it after the call to setupGUI().

Hope this saves some headache to others wanting the same thing :-)

No comments: