标签:Widget QT 示例 Menu void QAction 右键 new include
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QMenu>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
void contextMenuEvent(QContextMenuEvent *event) override;
void initMenu(void);
private:
QMenu *p_Menu;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include <QMessageBox>
#include <QAction>
Widget::Widget(QWidget *parent): QWidget(parent)
{
this->setContextMenuPolicy(Qt::DefaultContextMenu);
initMenu();
}
Widget::~Widget()
{
}
void Widget::initMenu(void)
{
p_Menu = new QMenu(this);
QAction *act1 = new QAction("act1");
QAction *act2 = new QAction("act2");
QAction *act3 = new QAction("act3");
QAction *act4 = new QAction("act4");
p_Menu->addAction(act1);
p_Menu->addAction(act2);
p_Menu->addAction(act3);
p_Menu->addAction(act4);
connect(act1, &QAction::triggered, this, [=]{QMessageBox::information(this, "title", "ac1");});
connect(act2, &QAction::triggered, this, [=]{QMessageBox::information(this, "title", "ac2");});
connect(act3, &QAction::triggered, this, [=]{QMessageBox::information(this, "title", "ac3");});
connect(act4, &QAction::triggered, this, [=]{QMessageBox::information(this, "title", "ac4");});
}
void Widget::contextMenuEvent(QContextMenuEvent *event)
{
Q_UNUSED(event);
p_Menu->exec(QCursor::pos());
}
标签:Widget,
QT,
示例,
Menu,
void,
QAction,
右键,
new,
include
From: https://www.cnblogs.com/linux-learn/p/18406085