문제

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!

도움이 되었습니까?

해결책

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();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top