PDA

View Full Version : Singleton Menu!



ArlexBee-871RBO
1st December 2009, 03:56
Greetings.

I have subclassed QPushButton, and I'll call it MyPushButton here. Each MyPushButton widget also has a menu associated with it, and I'll call that class NodeMenu. MyPushButton widgets are organized in a custom window, and the user has the ability to split the window unlimited number of times, which in turn creates a new set of MyPushButton widgets of the same kind.

Instead of dynamically creating a new NodeMenu for each MyPushButton widget of the same kind, I figured I should rewrite the NodeMenu class as a singleton. This is what it looks like in short:



class NodeMenu : public QMenu{

public:
typedef enum {MenuAnimation, MenuTransformers, MenuFractals, MenuColor} MenuType;

static NodeMenu *CreateMenu(MenuType menuType){

switch( menuType ){
case MenuAnimation:
static NodeMenu animationMenu(menuType);
return &animationMenu;

case MenuTransformers:
static NodeMenu transformersMenu(menuType);
return &transformersMenu;

case MenuFractals:
static NodeMenu fractalsMenu(menuType);
return &fractalsMenu;

case MenuColor:
static NodeMenu colorMenu(menuType);
return &colorMenu;
}
}

private:
NodeMenu(MenuType menuType);
NodeMenu(const NodeMenu &);
NodeMenu &operator=(const NodeMenu &);
~NodeMenu();
};



Now, this works fine, except I can't pass a QWidget *parent to the NodeMenu because if the very first created window is destroyed, then parent becomes a dangling pointer and I get seg-fault.

The NodeMenu doesn't seem to need a parent here, and the singleton gets destroyed during exit. But I would like to ask if anyone thinks there is anything wrong with this approach? I do save little bit of memory this way, but could this approach cause problems later on?

high_flyer
1st December 2009, 10:04
I figured I should rewrite the NodeMenu class as a singleton.
How come?

If you need multiple instances of your button, then Singleton is exactly what you DON'T need.

ArlexBee-871RBO
2nd December 2009, 01:47
How come?

If you need multiple instances of your button, then Singleton is exactly what you DON'T need.

I do need multiple instances of the button, but not the menu. Only one menu is shown at any given time.

high_flyer
2nd December 2009, 10:32
Sorry, I wrongly understood that you made your button a singleton.
How about using QAction instead of QMenu as base class?
I think that conceptually it is more correct.
Also, QAction is not a gui element, which makes it independent of any existing GUI elements, thus, instead giving it widgets, you give it to widgets.