Seb
Seb

Reputation: 3213

qt/c++ context menu - disable an item

I'm currently developing an app such as the browser using Qt and c++.

I have create a contextual menu to allow on right click action such as delete, rename and add folder.

void MyTreeWidget::createContextMenu() {    
    contextMenu = new QMenu();
    setContextMenuPolicy(Qt::ActionsContextMenu);

    addFolderAction = new QAction("Add Folder", contextMenu);
    addAction(addFolderAction);
    connect(addFolderAction, SIGNAL(triggered()),this,SLOT(onAddFolderActionTree()));

    deleteAction = new QAction("Delete", contextMenu);
    addAction(deleteAction);
    connect(deleteAction, SIGNAL(triggered()),this,SLOT(onDeleteAction()));

    RenameAction = new QAction("Rename", contextMenu);
    addAction(RenameAction);
    connect(RenameAction, SIGNAL(triggered()),this,SLOT(onRenameAction()));

}

This is working fine. This contextual menu is used when you select a file or folder in my treewidget and make a right click. My issue is that I propose the "add folder" option even if I select a file. You can't create a folder inside a file.

What I want is to disable the option when a file is selected and enable it when it's a folder.

I can know if it's file or folder by getting the TreeWidgetItem class I have overloaded:

Thanks

Upvotes: 4

Views: 4066

Answers (2)

Devan Williams
Devan Williams

Reputation: 1417

Use the QAction::setEnabled(bool) method on your 'addFolderAction'.

One way to use it is like this:

void
MyTreeWidget::updateMenuActions()
{
    if(!contextMenu)
        return;
    bool addFolderEnabled = <check TreeWidgetItem here to enable / disable>;
    addFolderAction->setEnabled(bEnabled);
}

Call the updateMenuActions() method just before you display the context menu.

I actually prefer the code below in case you have situations where you can have NULL pointers to actions (for cases where you don't even add them):

void
MyTreeWidget::updateMenuActions()
{
    if(!contextMenu)
        return;
    bool addFolderEnabled = <check TreeWidgetItem here to enable / disable>;
    updateAction(addFolderAction, bEditEnabled);
}

void
MyTreeWidget::updateAction(QAction* pAction, const bool& bEnabled)
{
    if(pAction)
        pAction->setEnabled(bEnabled);
}

Enjoy.

Upvotes: 2

Andrei Shikalev
Andrei Shikalev

Reputation: 722

You can disable QAction. In this case "Add Folder" menu item will be disabled:

addFolderAction->setEnabled(false);

Upvotes: 2

Related Questions