2013-02-05 29 views
2

我有一個QMenu,它有幾個動態構建的菜單項。使用QMenu並傳遞參數

爲此,我迭代了包含名稱和Action(如果菜單項被擊中時需要採取的操作)的菜單項集合,並不斷將它們添加到上下文菜單中。所有菜單項需要連接到到一個公共插槽

但不知何故,觸發器操作不會發生。即達到了連接語句,但控件不會傳遞到指定的SLOT中,則不採取任何操作。

for (int i=0; i<Action_List.size();i++) 
{ 
    tempAct1 = Action_List.at(i); //Action List has the list of Actions 
    Context_Menu->addAction(tempAct1); 
} 
if (Context_Menu!=NULL) { 
    Context_Menu->exec(QCursor::pos()); 
    int r = connect(Context_Menu, SIGNAL(triggered(QAction *)), 
        this, SLOT(SPlusCommand(QAction *))); 
} 

int P14MainWindow::SPlusCommand (QAction* Action) 
{ 
    QVariant tempstr = Action->data(); 
    QString Qs = tempstr.toString(); 
    return QPwLocalClient::ExecuteCommand(Qs); 
} 

任何人都可以告訴我哪裏出錯了嗎?

回答

4

好像你之前應該exec()移動connect

connect(Context_Menu, SIGNAL(triggered(QAction *)), 
     this, SLOT(SPlusCommand(QAction *))); 
Context_Menu->exec(QCursor::pos()); 

因爲exec執行菜單同步,什麼意味着它將從這個方法返回,只有當所有與菜單交互已經完成 - 爲時太晚而無法連接某些東西。

+0

非常感謝。這確實有效。 – user1173240

-2

您必須將個別操作與插槽連接。

connect(action, SIGNAL(triggered()), this, SLOT(yourSlot()) 
+0

不太對,因爲他想從插槽知道哪個動作被調用。 'QMenu :: triggered(QAction *)'信號也是合法的,正如[文檔](http://doc.qt.digia.com/stable/qmenu.html#triggered)所說的那樣,它是正確的:當您將多個*類似*操作連接到同一個插槽時。 – NIA