Qt中的上下文菜单 ContexMenu

Qt实现上下文菜单

一、重载contextMenuEvent()事件处理函数,在重载的contextMenuEvent函数中显示QMenu对象:

widget.h文件

#ifndef WIDGET_H
#define WIDGET_H
 
  
#include 
 
  
class QMenu;
class QAction;
 
  
namespace Ui {
class Widget;
}
 
  
class Widget : public QWidget
{
    Q_OBJECT
 
  
public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
protected:
    void contextMenuEvent(QContextMenuEvent *event);
 
  
private:
    Ui::Widget *ui;
    QMenu * menu;
    QAction * openAction;
    QAction * saveAsAction;
};
 
  
#endif // WIDGET_H


widget.cpp文件

#include "widget.h"
#include "ui_widget.h"
#include 
#include 
#include 

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget),
    menu(new QMenu(this)),
    openAction(new QAction(QStringLiteral("打开"), this)),
    saveAsAction(new QAction(QStringLiteral("另存为"), this))
{
    ui->setupUi(this);
    menu->addAction(openAction);
    menu->addAction(saveAsAction);
}

Widget::~Widget()
{
    delete ui;
}
void Widget::contextMenuEvent(QContextMenuEvent *event)
{
    //显示菜单到鼠标右击即event发生的坐标处,这两种写法都行,最终都是用全局坐标
    //this->menu->exec(this->mapToGlobal(event->pos()));
    this->menu->exec(event->globalPos());
}

二、添加QAction对象到父窗口,即要设置上下文菜单的窗口,然后设置父窗口属性为Qt::ActionsContextMenu:

只需将Widget类的构造函数做如下更改,并去掉对contextMenuEvent函数的重载:

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget),
    menu(new QMenu(this)),
    openAction(new QAction(QStringLiteral("打开"), this)),
    saveAsAction(new QAction(QStringLiteral("另存为"), this))
{
    ui->setupUi(this);
    //menu->addAction(openAction);
    //menu->addAction(saveAsAction);
    this->addAction(openAction);
    this->addAction(saveAsAction);
    this->setContextMenuPolicy(Qt::ActionsContextMenu);
}

 
 

你可能感兴趣的:(Qt笔记,Qt笔记)