PDA

View Full Version : [QMenu] Context menu for widget created in Qt Creator



Macok
4th March 2009, 15:49
I'd like to add context menus for widgets on my form.
As I know to do that I should reimplement Widget::contextMenuEvent(QContextMenuEvent*) function.
But how can I reimplement it if widget is created in Qt Creator (designer)?

@EDIT
Ok, I found out I can do it by this way:
void QLineEdit::contextMenuEvent ( QContextMenuEvent * event ){
QMenu *menu=new QMenu;
(...)
menu->exec(event->globalPos());
}But is there any way to set context menu for only one lineedit?

aamer4yu
4th March 2009, 17:06
That is one way... create your own custom widget and override the contextmenu event. From designer, you can promote the widget to your custom widget.

The other way is -
Set QWidget::setContextMenuPolicy to Qt::CustomContextMenu, and connect QWidget::customContextMenuRequested() signal to your handling class. and show the menu as you want in the global pos.

Macok
4th March 2009, 17:37
Thanks a lot.
I chose second method becouse first seems to be more complicated.
It works, but menu appears somewhere in the corner of my desktop.
I think I have to convert QPoint to global position, but how to do it?

@EDIT
Ok I found it.
Function to convert QPoint to global position is QPoint QWidget::mapToGlobal ( const QPoint & pos ) const

aamer4yu
5th March 2009, 07:27
Even QCursor::pos will give you global pos ;)

Use whatever suits you :)