[PyQt] Context menu on items in QTreeView

Russell Valentine russ at coldstonelabs.org
Tue Oct 14 21:50:21 BST 2008


Filip Gruszczyński wrote:
> Hello,
> 
> I would like to pop up a menu on items in QTreeView. I decided to
> intercept pressed(const QModelIndex&) signal, because contextMenuEvent
> doesn't provide information about the tree view chosen index. However,
> inside the slot for this signal I cannot acces position of the mouse
> (no event) and decide, where to pop this menu. I tried browsing
> QApplication class, but found no information about the global mouse
> position (though there is global information about buttons pressed).
> Is there anyway to obtain it and popup menu in the right place?
> 

Well there is QtGui.QCursor.pos()

So you can exec_ the menu using that.

You can use the indexAt function that is part of the treeview class and 
give it the cursor position to get the index.

I would connect to signal customContextMenuRequested instead of what 
your doing though.

Something like:

self.treeView.setContextMenuPolicy(QtCore.Qt.CustomConextMenu)
self.connect(self.treeview, 
QtCore.SIGNAL("customContextMenuRequested(const QPoint &)"), self.doMenu)


def doMenu(self, point)
         treeidx=self.treeview.indexAt(point)
	popupmenu.exec_(point)


Hope this is helpful.


Russell Valentine


More information about the PyQt mailing list