我有qplaintextedit
动态加载文字内容,QString
。
我想在右键单击qplaintextedit时显示的菜单中添加一个选项。如何以编程方式执行此操作以便我能够将自己的菜单项添加到默认菜单项?任何想法都将不胜感激。
答案 0 :(得分:1)
您可以升级QPlainTextEdit
并重新实施方法contextMenuEvent(QContextMenuEvent *event)
。或者,您可以向QPlainTextEdit
添加事件过滤器并捕获QContextMenuEvent
。
在您的实施中,您可以致电QMenu *QPlainTextEdit::createStandardContextMenu(const QPoint &position)
创建文字修改的默认菜单,然后将自定义项目添加到其中。
示例(子类):
void MyTextEdit::contextMenuEvent(QContextMenuEvent *event)
{
QMenu* menu = createStandardContextMenu(event->pos());
QAction* clearAction = menu->addAction("Clear");
QAction* choosedAction = menu->exec(event->globalPos());
//...
delete menu;
}
请参阅:
答案 1 :(得分:0)
您必须重新实现该功能:void QPlainTextEdit::contextMenuEvent(QContextMenuEvent *event)
此处的文档中提供了更多详细信息:http://doc.qt.io/qt-5/qplaintextedit.html#contextMenuEvent
答案 2 :(得分:0)
不必继承QPlainTextEdit的子类,也不必使用事件过滤器。您可以在应用程序的主窗口小部件中完成所有操作。以下使用Qt版本4.7.4和4.8.5对我有用。
在设计器中:
您添加了一个名为{textbox“的QPlainTextEdit
小部件。
在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;
...
}
在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;
}