views:

3046

answers:

3

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.

+2  A: 

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.

shoosh
+1  A: 

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());
}
Marius
tried this method, it had the same issue
Niall
+1  A: 

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.

David Dibben
Yes, using Qt 4.4. Thanks
Niall
I think this is fixed now. I'm using 4.4.3 and it seems to work okay.
Nick