PDA

View Full Version : CustomContextMenu with arguments



toodles
26th June 2012, 23:54
Hello,

Goal: Display a context menu under a clicked column header in QTableView(with a horizontal QViewHeader being the 'parent' of the actions), with one of the actions being "Hide Column" which would hide the selected/clicked on column.

Issue:I know how to have a context menu appear with regular actions that trigger functions with no arguments but how do I pass an argument(a column number specifically) to this slot function?

Approach:My approach thus far has been to set the horziontal header's setContextMenuPolicy as Qt::CustomContextMenu, and then trigger a function like showContextMenu(const QPoint&).

showContextMenu(..)
QAction* hide = new QAction(tr("Hide Column"),this);
QMenu* popUp = new QMenu("Column Menu", this);
popUp->addAction(hide);
popUp->popup(mapToGlobal(p));

My goal is determine if I can get something like connect(hide, SIGNAL(triggered()), this, SLOT(hideColumn(int))); to work but my attempts have been unsuccessful. How do I do this or is there a better way to do this?

I hope I've made my issue clear.

mentalmushroom
27th June 2012, 08:14
take a look at QSignalMapper

toodles
27th June 2012, 14:07
If I have only one menu item "Hide Column" under the context menu, how would I know "signalMapper->setMapping(hideAction, ?...?);" what to pass in the 2nd argument of that function? There is only one hide action for all the columns, now the issue is to determine under which column it was pressed. The custom context menu would pass a const QPoint& which makes this slightly harder but I still don't see how its done.

What do I do ?

mentalmushroom
27th June 2012, 14:25
before you show the popup find out what column was clicked. then connect your hide action to QSignalMapper map slot and set mapping of your action to the column id. then connect QSignalMapper's mapped signal to your slot with one argument of type int. you can find QSignalMapper usage sample in the docs.

or maybe easier would be to call setData passing the obtained column id instead of using QSignalMapper. also you may save the clicked column id to some member variable and use it in your slot.