2012-11-26 60 views
3

我想創建一個QMenu,其中包含可檢查的QAction對象。一旦選中某個動作,它就會觸發並啓用某個3D對象的繪製。但是,3D對象的數量取決於要加載的文件。因此,這個QMenu具有動態數量的QAction對象。假設我們有10個名爲「1」,「2」,...「10」的3D對象,因此QMenu中的QAction對象將顯示爲「1」,「2」,...「10」。當其中一個選中時,該名稱的3D對象將被啓用顯示。Qt QAction動態陣列連接

代碼生成動態的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的切換信號只通過一個布爾值。理想情況下,我會在defaultScene一個單一的功能:

void toggleObject3D(int index){ 
    if(index >= 0 && index < visibleSize){ 
      visible[index] = !visible[index]; 
    } 
} 

因此,爲了使這項工作,我需要從traceMenu某種信號會觸發一個int變量。我不知道這樣的信號。

回答

5

可以使用QSignalMapperLink in the documentation

的想法是每的QAction與索引關聯,然後使用來自QSignalMapper映射(INT)信號。當然,我們需要映射切換的信號。

首先,將您的方法toggleObject3D定義爲插槽。

然後,產生的QA​​ction的實例時,創建QSignalMapper與它的每個動作關聯:

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

,它應該工作:)

+0

謝謝你,這相當奏效 – ChaoSXDemon