Hello, i need to create a context menu on right clicking at my window. But i really don't know what should i do. Are there any widgets or i must make it by my hands? Programming language: Python Graphical lib: Qt (PyQt).
+3
A:
It is possible, but usually more of a problematic feature. I've tried this before, and found it's much easier to have a Menu bar with buttons.
jcoon
2009-04-23 15:34:01
Thanks, but what basic methods are there?
Ockonal
2009-04-23 15:35:45
+12
A:
I can't speak for python, but it's fairly easy in C++.
first after creating the widget you set the policy:
w->setContextMenuPolicy(Qt::CustomContextMenu);
then you connect the context menu event to a slot:
connect(w, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(ctxMenu(const QPoint &)));
Finally, you implement the slot:
void A::ctxMenu(const QPoint &pos) {
QMenu *menu = new QMenu;
menu->addAction(tr("Test Item"), this, SLOT(test_slot()));
menu->exec(w->mapToGlobal(pos));
}
that's how you do it in c++ , shouldn't be too different in the python API.
EDIT: after looking around on google, here's the setup portion of my example in python:
self.w = QWhatever();
self.w.setContextMenuPolicy(Qt.CustomContextMenu)
self.connect(self.w,SIGNAL('customContextMenuRequested(QPoint)'), self.ctxMenu)
Evan Teran
2009-04-23 16:14:44
+3
A:
Another example which shows how to use actions in a toolbar and context menu.
class Foo( QtGui.QWidget ):
def __init__(self):
QtGui.QWidget.__init__(self, None)
# Toolbar
toolbar = QtGui.QToolBar()
# Actions
self.actionAdd = toolbar.addAction("New", self.on_action_add)
self.actionEdit = toolbar.addAction("Edit", self.on_action_edit)
self.actionDelete = toolbar.addAction("Delete", self.on_action_delete)
# Tree
self.tree = QtGui.QTreeView()
self.tree.setContextMenuPolicy( Qt.CustomContextMenu )
self.connect(self.tree, QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'), self.on_context_menu)
# Popup Menu
self.popMenu = QtGui.QMenu( self )
self.popMenu.addAction( self.actionEdit )
self.popMenu.addAction( self.actionDelete )
self.popMenu.addSeparator()
self.popMenu.addAction( self.actionAdd )
def on_context_menu(self, point):
self.popMenu.exec_( self.tree.mapToGlobal(point) )
PedroMorgan
2009-06-06 04:07:47