标签:菜单 qt上下文菜单 menu qmenu 上下文菜单
上下文菜单可通过鼠标右键点击弹出。主要描述下基本的上下文菜单的框架应该怎么写。
只要涉及菜单的操作一般使用 QMenu 和QAction 都能够解决。
void MainWindow::contextMenuEvent(QContextMenuEvent *e)
{
popmenu->addAction(copyAction);
popmenu->addAction(pasteAction);
popmenu->addAction(deletAction);
popmenu->exec(QCursor::pos());
e->accept();
}
完整代码如下
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QContextMenuEvent>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
private:
Ui::MainWindow *ui;
QMenu *popmenu;
QAction *copyAction;
QAction *pasteAction;
QAction *deletAction;
void contextMenuEvent(QContextMenuEvent *);
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
popmenu = new QMenu(this);
copyAction = new QAction("copy",this);
pasteAction = new QAction("paste",this);
deletAction = new QAction("delete",this);
copyAction->setIcon(QIcon(":/Icon/copy.png"));
pasteAction->setIcon(QIcon(":/Icon/parst.png"));
deletAction->setIcon(QIcon(":/Icon/delet.png"));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::contextMenuEvent(QContextMenuEvent *e)
{
popmenu->addAction(copyAction);
popmenu->addAction(pasteAction);
popmenu->addAction(deletAction);
//弹出的位置为当前光标的位置
popmenu->exec(QCursor::pos());
e->accept();
}
通过在构造函数中直接加入action
然后使用setContextMenuPolicy设置为ActionsContextMenu
copyAction = new QAction("copy",this);
pasteAction = new QAction("paste",this);
deletAction = new QAction("delete",this);
copyAction->setIcon(QIcon(":/Icon/copy.png"));
pasteAction->setIcon(QIcon(":/Icon/parst.png"));
deletAction->setIcon(QIcon(":/Icon/delet.png"));
addAction(copyAction);
addAction(pasteAction);
addAction(deletAction);
setContextMenuPolicy(Qt::ActionsContextMenu);
效果如下:
标签:菜单 qt上下文菜单 menu qmenu 上下文菜单
原文地址:http://blog.csdn.net/tianzhihen_wq/article/details/44515955