鼠标事件是学习Qt必不可少的一个事件,初学者总是会忽略这一点,而右键菜单在平常的使用中更是常见,下面就Qt中添加右键菜单的几种方法做一简单的介绍:
1、鼠标事件添加
/**重写鼠标处理器*/
void QWidget::mousePressEvent(QMouseEvent * event) 或者
void QWidget::mouseReleaseEvent(QMouseEvent * event)
当窗口接收到信号是判断鼠标的哪一个键被按下:
/**定义菜单和要添加的事件*/
QMenu *m_pwebMenu;
QAction *m_pActionDelete;
QAction *m_pActionResend;
/**初始化Menu和Action*/
m_pwebMenu = new QMenu( this );
m_pActionDelete = new QAction( tr( "DELETE" ), this );
m_pActionResend = new QAction( tr( "RESEND" ), this );
/**将Action添加到Menu中*/
m_pwebMenu->addAction( m_pActionResend );
m_pwebMenu->addAction( m_pActionDelete );
/**显示菜单*/
m_pwebMenu->exec( QCursor::pos() );
上述方法显示右键菜单是使用的是屏幕的坐标,使用QCursor类的静态函数pos()可以快速的定位鼠标按下时的坐标。
2、使用和右键菜单有关的setContextMenuPolicy()函数:
void setContextMenuPolicy(Qt::ContextMenuPolicy policy)为QWidget的成员函数,从QWidget直接或间接派生的类都可以使用该函数对右键菜单进行设置。
Qt::ContextMenuPolicy是一个枚举类型,包括:
Qt::NoContextMenu、Qt::PreventContextMenu、Qt::DefaultContextMenu、Qt::ActionsContextMenu、Qt::CustomContextMenu
其中Qt::NoContextMenu、Qt::PreventContextMenu 不能实现右键菜单的功能。
l Qt::DefaultContextMenu
设置此属性需要重写
void QWidget::contextMenuEvent(QContextMenuEvent * event)
事件处理器函数来实现右键菜单
void Widget::contextMenuEvent(QContextMenuEvent *ev)
{
/**初始化Menu和Action*/
m_pwebMenu = new QMenu( this );
m_pActionDelete = new QAction( tr( "DELETE" ), this );
m_pActionResend = new QAction( tr( "RESEND" ), this );
/**将Action添加到Menu中*/
m_pwebMenu->addAction( m_pActionResend );
m_pwebMenu->addAction( m_pActionDelete );
/**显示菜单*/
m_pwebMenu->exec( QCursor::pos() );
}
l Qt::ActionsContextMenu
设置此属性后添加到当前窗口中所有QAction都会作为右键菜单项显示出来
在窗口构造函数中设置右键菜单的处理方式:
setContextMenuPolicy(Qt:: ActionsContextMenu)
在当前窗口中添加QAction:
/**初始化Menu和Action*/
m_pwebMenu = new QMenu( this );
m_pActionDelete = new QAction( tr( "DELETE" ), this );
m_pActionResend = new QAction( tr( "RESEND" ), this );
/**将Action添加到Menu中*/
m_pwebMenu->addAction( m_pActionResend );
m_pwebMenu->addAction( m_pActionDelete );
/**显示菜单*/
m_pwebMenu->exec( QCursor::pos() );
l Qt:: CustomContextMenu
它是发出QWidget::customContextMenuRequested信号,注意仅仅只是发信号,意味着要自己写显示右键菜单的槽函数(slot)这个信号是QWidget唯一与右键菜单有关的信号(也是自有的唯一信号),同时也是很容易被忽略的signal:
void customContextMenuRequested ( const QPoint & pos )
该信号的发出条件是:用户请求contextMenu(常规就是鼠标右击)且同时被击的widget其contextMenuPolicy又是Qt::CustomContextMenu。
注意: 信号中的参数pos为当前窗口的坐标,并非屏幕坐标。
m_ui.webView->setContextMenuPolicy(Qt::CustomContextMenu);
connect( m_ui.webView, SIGNAL(customContextMenuRequested(QPoint)),
SLOT( slot_webViewRightClicked( QPoint ) ) );
void chatdemo::slot_webViewRightClicked(const QPoint &pos)
{
m_pwebMenu = new QMenu( this );
m_pActionDelete = new QAction( tr( "DELETE" ), this );
m_pActionResend = new QAction( tr( "RESEND" ), this );
m_pwebMenu->addAction( m_pActionResend );
m_pwebMenu->addAction( m_pActionDelete );
m_pwebMenu->exec( QCursor::pos() );
}