Reputation: 8292
I have a qplaintextedit
that is loaded dynamically with text contents, with QString
.
I want to add an option to the menu that appears when we right click on the qplaintextedit. How can I do it programmatically so that I am able to add my own menu item to the default menu item? Any ideas would be appreciated.
Upvotes: 0
Views: 1789
Reputation: 877
It is not necessary to subclass QPlainTextEdit, nor to use an event filter. You can do it all in the main widget of your application. The following worked for me using Qt versions 4.7.4 and 4.8.5.
In the Designer:
You add a QPlainTextEdit
widget whose name is "textbox".
In MainWindow.h:
// Auto generated from MainWindow.ui
#include "ui_MainWindow.h"
class MainWindow : public QMainWindow
{
Q_OBJECT
private:
/// The auto generated user interface.
Ui::MainWindowClass ui;
...
}
In MainWindow.cpp:
MainWindow::MainWindow( QWidget * pParent, Qt::WFlags flags )
: QMainWindow( pParent, flags )
, ui( )
{
ui.textbox->setContextMenuPolicy( Qt::CustomContextMenu );
connect( ui.textbox, SIGNAL( customContextMenuRequested( QPoint ) ),
this, SLOT( onTextboxCustomContextMenuRequested( QPoint ) ) );
}
void MainWindow::onTextboxCustomContextMenuRequested( QPoint p )
{
// Start with the standard menu.
QMenu * pMenu = ui.textbox->createStandardContextMenu();
QAction * pAction;
// Clear.
// Because QPlainTextEdit::clear() is a slot method, I can connect directly to it.
pAction = new QAction( "Clear", this );
connect( pAction, SIGNAL( triggered() ), ui.textbox, SLOT( clear() ) );
pMenu->addAction( pAction );
// Show the menu.
QPoint q = ui.textbox->mapToGlobal( p );
pMenu->exec( q );
// The menu's ownership is transferred to me, so I must destroy it.
delete pMenu;
}
Upvotes: 0
Reputation: 2602
You can sublcass QPlainTextEdit
and reimplement the method contextMenuEvent(QContextMenuEvent *event)
. Alternatively you can add an event filter to a QPlainTextEdit
and catch the QContextMenuEvent
.
In your implementation, you can call QMenu *QPlainTextEdit::createStandardContextMenu(const QPoint &position)
to create the default menu of the text edit and than add your custom items to it.
Example (subclass):
void MyTextEdit::contextMenuEvent(QContextMenuEvent *event)
{
QMenu* menu = createStandardContextMenu(event->pos());
QAction* clearAction = menu->addAction("Clear");
QAction* choosedAction = menu->exec(event->globalPos());
//...
delete menu;
}
See:
Upvotes: 1
Reputation: 279
You have to reimplement the function : void QPlainTextEdit::contextMenuEvent(QContextMenuEvent *event)
More details in the doc here : http://doc.qt.io/qt-5/qplaintextedit.html#contextMenuEvent
Upvotes: 0