我想创建一个 QMenu,其中包含可检查的 QAction 对象。一旦选中一个 Action ,它将触发并启用某些 3D 对象的绘制。但是,3D 对象的数量取决于要加载的文件。因此,此 QMenu 具有动态数量的 QAction 对象。假设我们有 10 个 3D 对象,名称为“1”、“2”、...“10”,因此 QMenu 中的 QAction 对象将显示为“1”、“2”、...“10”。选中其中一项后,将启用显示该名称的 3D 对象。
生成动态 QAction 对象的代码:
QStringList labels = defaultScene->getLabels();
for(int i=0; i<labels.size(); i++){
QAction* labelAction = new QAction(labels[i], this);
labelAction->setToolTip("Trace Marker " + labels[i]);
labelAction->setStatusTip("Trace Marker " + labels[i]);
labelAction->setCheckable(true);
traceMenu->addAction(labelAction);
}
我的问题是,如何连接这些 QAction 对象?具体来说,我在 defaultScene 中有一个 bool 数组,它将随着 QAction 的切换而切换。我怎么知道哪个 QAction 正在触发?切换时 QAction 的 SIGNAL 仅通过 bool。理想情况下,我会在 defaultScene 中有一个函数:
void toggleObject3D(int index){
if(index >= 0 && index < visibleSize){
visible[index] = !visible[index];
}
}
因此,为了使这项工作正常进行,我需要来自 traceMenu 的某种 SIGNAL,它会触发一个 int 变量。我不知道有这样的信号。
最佳答案
您可以使用QSignalMapper
( Link in the documentation )
想法是将每个 QAction 与一个索引相关联,然后使用来自 QSignalMapper 的 mapped(int) 信号。当然,我们需要映射切换信号。
首先,将您的方法 toggleObject3D 定义为插槽。
然后,在生成 QAction 的实例时,创建 QSignalMapper 并将每个 Action 与其相关联:
QStringList labels = defaultScene->getLabels();
QSignalMapper *mapper = new QSignalMapper(this);
for(int i=0; i<labels.size(); i++){
QAction* labelAction = new QAction(labels[i], this);
labelAction->setToolTip("Trace Marker " + labels[i]);
labelAction->setStatusTip("Trace Marker " + labels[i]);
labelAction->setCheckable(true);
traceMenu->addAction(labelAction);
// Map this action to index i
mapper->setMapping(labelAction, i);
// Associate the toggled signal to map slot from the mapper
// (it does not matter if we don't use the bool parameter from the signal)
connect(action, SIGNAL(toggled(bool)), mapper, SLOT(map()));
}
// Connect the QSignalMapper map() signal to your method
connect(mapper, SIGNAL(mapped(int)), this, SLOT(toggleObject3D(int)));
它应该可以工作:)
关于c++ - Qt QAction 动态数组连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13557886/