Question

I want to add some QAction dynamically from settings file :

_settings.beginGroup("openRecent");
QStringList recentList = _settings.childKeys();

foreach(QString recentFile, recentList)
{
    QAction * action = new QAction(_settings.value(recentFile, "empty").toString(), this);
    action->setObjectName(_settings.value(recentFile, "empty").toString());
    connect(action, SIGNAL(triggered()), this,  openFile(action->objectName()));
    _recentFileButtons.append(action);
}
_settings.endGroup();

which fails to compile due to this line connect(action, SIGNAL(triggered()), this, openFile(action->objectName()));

Question :

How do I connect a QAction to a given function (with parameters)?

Was it helpful?

Solution 2

You cannot pass parameters in that way. I would suggest to do the following:

connect(action, SIGNAL(triggered()), this, SLOT(openFile()));

And in your openFile() slot just do:

void MyClass::openFile()
{
    QObject *obj = sender();
    QString objName = obj->objectName();
    [..]
}

OTHER TIPS

you can't, not directly

there are 2 options available:

  1. use sender() to get the sending QObject and use that

  2. use a QSignalMapper which will add a single parameter to the signal

    signalMapper->setMapping(action, action->objectName());
    connect(action, SIGNAL(triggered()), signalMapper,  SLOT(map()));
    

    and connect signalMapper to this:

    connect(signalMapper, SIGNAL(mapped(QString)), this,  SLOT(openFile(QString)));
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top