- 用到头文件
qmenu.h qevent.h qlabel.h - 代码
#pragma once
// QtTestMenu2.h
#include <QtWidgets/QWidget>
#include "ui_QtTestMenu2.h"
#include "qmenu.h"
#include "qevent.h"
#include "qlabel.h"class QtTestMenu2 : public QWidget
{Q_OBJECTpublic:QtTestMenu2(QWidget *parent = nullptr);~QtTestMenu2();virtual void mousePressEvent(QMouseEvent*);
private:void createMenu();
private slots:void slotMenuClicked(QAction*);
private:Ui::QtTestMenu2Class ui;QMenu* m_pMenu;QAction* m_pActionAdd;QAction* m_pActionDel;QAction* m_pActionEdit;QMenu* m_pMenuTest;QAction* m_pActionTest1;QAction* m_pActionTest2;QLabel* mLab;
};QtTestMenu2.cpp#include "QtTestMenu2.h"QtTestMenu2::QtTestMenu2(QWidget *parent): QWidget(parent), mLab(new QLabel(this))
{ui.setupUi(this);mLab->setMinimumSize(QSize(this->width() / 2, this->height() / 2));createMenu();
}QtTestMenu2::~QtTestMenu2()
{}void QtTestMenu2::mousePressEvent(QMouseEvent* e)
{if (e->button() == Qt::RightButton) {m_pMenu->exec(QCursor::pos());}
}void QtTestMenu2::createMenu()
{m_pMenu = new QMenu(this);m_pActionAdd = m_pMenu->addAction(tr("Add"));m_pActionDel = m_pMenu->addAction(tr("Del"));m_pActionEdit = m_pMenu->addAction(tr("Edit"));m_pMenu->addSeparator();QIcon icon(QPixmap("f://test.jpg"));m_pMenu->addMenu(icon,"test QIcon");m_pMenuTest = new QMenu(this);m_pMenuTest->setTitle(tr("Test"));m_pActionTest1 = m_pMenuTest->addAction(tr("Test1"));m_pActionTest2 = m_pMenuTest->addAction(tr("Test2"));m_pMenu->addMenu(m_pMenuTest);connect(m_pMenu, &QMenu::triggered, this, &QtTestMenu2::slotMenuClicked);
}void QtTestMenu2::slotMenuClicked(QAction* ac)
{if (ac == m_pActionAdd) {this->mLab->setText("Add");} else if (ac == m_pActionDel) {this->mLab->setText("Del");} else if (ac == m_pActionEdit) {this->mLab->setText("Edit");} else if (ac == m_pActionTest2) {this->mLab->setText("Test2");} else if (ac == m_pActionTest1) {this->mLab->setText("Test1");}
}
//
-
显示效果
-
代码结构说明
4.1 重写 mousePressEvent 当鼠标右键按下将菜单栏显示到鼠标点击位置
4.2 点击菜单栏的项目触发 triggered(QAction*) 信号, 我们在槽函数中对信号进行反馈;
4.3 初始化就添加菜单栏和选项