0

我想QAction从设置文件中动态添加一些:

_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();

由于这一行而无法编译connect(action, SIGNAL(triggered()), this, openFile(action->objectName()));

问题 :

如何将 QAction 连接到给定函数(带参数)?

4

2 回答 2

4

你不能,不能直接

有 2 个选项可用:

  1. 用于sender()获取发送 QObject 并使用它

  2. 使用QSignalMapper将单个参数添加到信号

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

    并连接signalMapperthis

    connect(signalMapper, SIGNAL(mapped(QString)), this,  SLOT(openFile(QString)));
    
于 2013-11-19T15:17:42.623 回答
1

您不能以这种方式传递参数。我建议执行以下操作:

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

在您的openFile()插槽中,只需执行以下操作:

void MyClass::openFile()
{
    QObject *obj = sender();
    QString objName = obj->objectName();
    [..]
}
于 2013-11-19T15:15:42.810 回答