QTreeView Context Menus

  • Hi All,

    I'm having some issues with context menus in QTreeViews, where i can't explain why an action in a menu appears to be disabled. The menu action 'colour' apears but it can't be selected, and no signal is transmitted.

    TreeView Constructor:

           connect(ui->ui_treeView, SIGNAL(customContextMenuRequested(QPoint)),
                       this, SLOT(ContextMenuRequested(QPoint)));

    TreeView ContextMenuRequested function:

    void TreeView::ContextMenuRequested(const QPoint &pos)
      QModelIndex index = ui->ui_treeView->indexAt(pos);
           IElement* genericelement = static_cast<IElement*>(index.internalPointer());
           IModelElement* modelElement = dynamic_cast<IModelElement*>(genericelement);
                QMenu* menu = modelElement->getContextMenu();

    ModelElement Constructor:

    m_contextMenu = new QMenu();
      m_colourAction = new QAction(tr("Colour"),this);
    QMenu *IModelElement::getContextMenu()
      return m_contextMenu;
    void IModelElement::context_Colour()
      qDebug() << this->getName() << " changing colour";

    As you can see from the above code extracts the menu is constructed and the signal connected for each model element, and each element supplies it's own menu to the view (so they can be customized), and each has it's own action connected to a function which should just provide the debug statement. There are no signal mapping error shown in the program output, suggesting the signals are mapped correctly.

    Does anyone have any ideas?

  • Lifetime Qt Champion


    Good question but I haven't had the use case. One thing that looks "incorrect" is that you don't add your action to the menu the usual way:

    m_colourAction = m_contextMenu->addAction(tr("Colour"));

    If not, then you should also make the menu the parent of your QAction rather than your IModelElement.

    Out of curiosity, why the two casts one after the other ? You should also rather use qobject_cast since your IModelElement is also a QObject.

    On a side note, did you take into account the memory consumption of your model ? You are creating as many menus and actions (and also QObjects) as you have elements in your model for a functionality that doesn't really demand it.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.