我的问题是制作一个菜单来加载文件。这是我的代码:
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没有我可以得到的信号 其名称。怎么解决这个?谢谢!
答案 0 :(得分: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();
}