PDA

View Full Version : QSignalMapper, QMenu and custom context menu



NameRakes
3rd January 2017, 05:23
Thanks to this thread (http://www.qtcentre.org/threads/49971-QTreeView-and-dynamic-context-menu), I discovered QSignalMapper, and found this nice example in Qt's doc:



ButtonWidget::ButtonWidget(const QStringList &texts, QWidget *parent)
: QWidget(parent)
{
signalMapper = new QSignalMapper(this);

QGridLayout *gridLayout = new QGridLayout;
for (int i = 0; i < texts.size(); ++i) {
QPushButton *button = new QPushButton(texts[i]);
connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
signalMapper->setMapping(button, texts[i]);
gridLayout->addWidget(button, i / 3, i % 3);
}

connect(signalMapper, SIGNAL(mapped(QString)),
this, SIGNAL(clicked(QString)));

setLayout(gridLayout);
}


My question is: can I use the above approach with custom context menus, thus?


class MyCustomMenu : QMenu {
/* do as above except map (QAction*, actionText) through signalMapper */
};

Would this work? If not this, what do most people do when you have a long list (say, more than 5-8) of context menu actions?

Thanks for your insightful comments.

Added after 1 40 minutes:

As it happens, my Google search before my posting was not useful. It's funny how juxtaposing a few words in Google search fetches a different set of hits ... this link (https://asmaloney.com/2015/05/code/qsignalmapper-example-revisited/)clearly illustrates what I want to do, that too with the function pointer idiom, which is better, except if you have overloading. Even with overloading it is not at all bad.

Still I would like the opinion of Qt experts on the choice of idioms. Thanks.

anda_skoa
3rd January 2017, 10:07
Would this work? If not this, what do most people do when you have a long list (say, more than 5-8) of context menu actions?

Yes, basically the same code, just using the action's "triggered()" signal instead of a button's "clicked()" signal.

Cheers,
_