1
votes

I have a QTreeView class with a context menu installed as follows:

m_ui.tree->setContextMenuPolicy(Qt::CustomContextMenu);
connect(m_ui.tree, SIGNAL(customContextMenuRequested(const QPoint&)),
        this, SLOT(ShowTreeContextMenu(const QPoint&)));
...
void ShowTreeContextMenu(const QPoint& point)
{
   m_treeContextMenu->exec(m_ui.tree->viewport()->mapToGlobal(point));
}

However when the context menu is being displayed the QTreeView will no longer respond to mouse clicks. Clicking on an item in the QTreeView while the context menu is displayed will remove the context menu but does not select the clicked item.

This is especially disorientating when right clicking on a new item, as the context menu pops up over the new item, but as the item was not selected the contents of the context menu are referring to the previously selected item.

3
I think this is now fixed in Qt 4.4.3Nick

3 Answers

2
votes

A possible solution which I haven't verified would be to capture the click event of the right click, manually make the selection in the tree view and then invoking the parent click event which will in turn activate the context menu.

1
votes

Subclass the QTreeView and add the protected method void contextMenuEvent(QContextMenuEvent *event); In this method you execute a QMenu:

class TreeView : public QTreeView{
  Q_OBJECT
public:
  TreeView(QWidget *parent);
  ~TreeView();
protected:
  void contextMenuEvent(QContextMenuEvent *event);
};

void TreeView::contextMenuEvent(QContextMenuEvent *event){
  QMenu menu(this);
  menu.addAction(action1);
  menu.addAction(action2);
  //...
  menu.addAction(actionN);
  menu.exec(event->globalPos());
}
1
votes

You don't say which version of Qt you are using, but we found the same problem in Qt4.4.0, it worked in 4.3. We reported this to Trolltech as a bug 225615

This is still marked as pending, so in the meantime I would follow Shy's suggestion of intercepting the right click and making the selection yourself.