编写Qt界面程序的时候,经常会用到右键菜单(ContextMenu),目前自己知道的创建右键菜单的方法有两种,
方法1:在mousePressEvent事件中判断鼠标按下的是否是右键,进而调用创建右键菜单的函数。
void Dialog::mousePressEvent(QMouseEvent *event)//鼠标按下事件 { if(event->button() == Qt::RightButton) { createContextMenu(); } } void Dialog::createContextMenu()//创建右键菜单函数 { QCursor cur=this->cursor(); QMenu *contextMenu = new QMenu(this); QAction *cutAction = new QAction(tr("&New"), this); cutAction->setShortcut(QKeySequence::New); QAction *copyAction = new QAction(tr("&Copy"), this); copyAction->setShortcut(QKeySequence::Copy); QAction *pasteAction = new QAction(tr("&Paste"), this); pasteAction->setShortcut(QKeySequence::Paste); contextMenu->addAction(cutAction); contextMenu->addAction(copyAction); contextMenu->addAction(pasteAction); contextMenu->exec(cur.pos()); }
void Dialog::contextMenuEvent(QContextMenuEvent *event)//重写右键菜单 { QCursor cur=this->cursor(); QMenu *contextMenu = new QMenu(this); QAction *cutAction = new QAction(tr("&New"), this); cutAction->setShortcut(QKeySequence::New); QAction *copyAction = new QAction(tr("&Copy"), this); copyAction->setShortcut(QKeySequence::Copy); QAction *pasteAction = new QAction(tr("&Paste"), this); pasteAction->setShortcut(QKeySequence::Paste); contextMenu->addAction(cutAction); contextMenu->addAction(copyAction); contextMenu->addAction(pasteAction); //setContextMenuPolicy(Qt::ActionsContextMenu); contextMenu->exec(cur.pos()); }