Question

My problem is to make a menu to load files. Here's my code:

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*)));
}

And a slot:

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

After I click any action button, qDebug shows:

"file1"
"file1"
"file1"

But I need to run that action only once! QAction does not have a signal from which I can get its name. How to solve this? Thank you!

Était-ce utile?

La solution

The problem is that you create the same connection tree times in the loop. What you probably need, is just doing it only once:

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

UPDATE

The alternative solution would be:

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

with the corresponding slot:

void MainWindow::load() {
    QAction *action = qobject_cast<QAction *>(sender());
    if (action)
        qDebug() << action->text();
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top