0

我的问题是制作一个菜单来加载文件。这是我的代码:

QStringList fileNameList;
fileNameList << "file1" << "file2" << "file3";
QMenuBar *menubar = new QMenuBar();
QMenu *menu = menubar->addMenu("File");
QMenu *load = menu->addMenu("Load");
foreach (QString fileName, fileNameList) {
    QAction *loadFile = new QAction(fileName, this);
    load->addAction(loadFile);
    connect(load,SIGNAL(triggered(QAction*)),this, SLOT(load(QAction*)));
}

还有一个插槽:

void MainWindow::load(QAction* action) {
    qDebug() << action->text();
}

单击任何操作按钮后,qDebug 显示:

"file1"
"file1"
"file1"

但我只需要运行一次该操作!QAction 没有我可以从中获得其名称的信号。如何解决这个问题?谢谢!

4

1 回答 1

2

问题是您在循环中创建了相同的连接树时间。您可能需要的只是执行一次:

[..]
foreach (QString fileName, fileNameList) {
    QAction *loadFile = new QAction(fileName, this);
    load->addAction(loadFile);
}
connect(load, SIGNAL(triggered(QAction *)), this, SLOT(load(QAction *)));

更新

替代解决方案是:

foreach (QString fileName, fileNameList) {
    QAction *loadFile = new QAction(fileName, this);
    load->addAction(loadFile);
    connect(loadFile, SIGNAL(triggered()), this, SLOT(load()));
}

与相应的插槽:

void MainWindow::load() {
    QAction *action = qobject_cast<QAction *>(sender());
    if (action)
        qDebug() << action->text();
}
于 2014-03-06T12:54:31.237 回答