我的这个类名是AddressbookWidget继承自QWidget
重写void QWidget::contextMenuEvent ( QContextMenuEvent * event ) [virtual protected]
void AddressbookWidget::contextMenuEvent(QContextMenuEvent *)
{
QMenu *popMenu = new QMenu(personInfo_List); //菜单添加在personInfo_List这个对象里面
QAction *towhite = new QAction(tr("到白名单") , personInfo_List); //右键显示的菜单
QAction *toblack = new QAction(tr("到黑名单") , personInfo_List);
connect(towhite , SIGNAL(triggered(bool)) , this , SLOT(menu_white())); //右键菜单事件
connect(toblack , SIGNAL(triggered(bool)) , this , SLOT(menu_black())); //右键菜单事件
if(personInfo_List->itemAt(mapFromGlobal(QCursor::pos())) != NULL) //mapFromGlobal全局位置的映射
{
popMenu->addAction(towhite); //将菜单标签加载上去显示
popMenu->addAction(toblack);
}
popMenu->exec(QCursor::pos()); //菜单出现的位置为当前鼠标的位置
delete popMenu;
delete towhite;
delete toblack;
}
信号和槽的连接
connect(towhite , SIGNAL(triggered(bool)) , this , SLOT(menu_white()));
connect(toblack , SIGNAL(triggered(bool)) , this , SLOT(menu_black()));
menu_white()和menu_black()是AddressbookWidget中的成员函数,这里面实现了右键单击菜单后点击菜单所要实现的功能(what to do....)。