PDA

View Full Version : QTreeView and dynamic context menu



dvlpr
13th July 2012, 17:39
Hello,

I have a fairly common requirement: provide a QTreeView with context menu depending of what type of element in the tree is selected, some of the actions creating child items in the QTreeView.

I have therefore set the context menu of my QTreeView to Qt::CustomContextMenu and I am creating the menu and actions in a 'showContextMenu(const QPoint& pnt)' slot. Great so far.

What seems like a clean design is then to call in this slot a 'createMenu()' method on the model item and via polymorphism or static policies this item class would return the proper menu with proper actions etc. Ok so far.

Now what makes things cumbersome to create child items is that I have to connect the actions 'triggered' signal to some slot:
- If the slot is in my specialized item class it is better loose coupling, but it means that to actually add a child to the QTreeView I would need to pass the model or the selection model to the item to call 'beginInsertRows' etc... Weird!
- If the slot is in my QTreeView derivate class, I would have to have as much slots as all the menu actions required by all the item classes appearing in the QTreeView, which in terms of coupling seems not that good ...
- If I setup some 'a la visitor pattern' call where a generic 'addChild()' slot in my QTreeView derivative class calls the item 'addChild()' method for specific behavior, I cannot determine which action was triggered except by checking sender of signal against all the actions available ... same coupling as in the previous point.

If someone has a hint on how to proceed I would be grateful if you could help me.

Thanks a lot for your answers!

d_stranz
13th July 2012, 20:22
If you use the second solution, I think you could implement this using a single slot, and use QSignalMapper to funnel all of the child signals through one slot. Read up on that to see if it might work.

dvlpr
17th July 2012, 10:01
Hello,

Thank you, the QSignalMapper trail was useful.

All in all I implemented a factory for the QMenu objects and the signal mapper dispatches signals to create the right menu.

Regards,
Jean-Paul