欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

QMenuBar QMenu 自定义菜单栏 基本控件(八)

程序员文章站 2022-05-28 11:38:11
...

一、效果图
QMenuBar QMenu 自定义菜单栏 基本控件(八)
二、代码

#include "menuwidget.h"
#include "ui_menuwidget.h"
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QDebug>
#include <QKeySequence>
menuWidget::menuWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::menuWidget)
{
    ui->setupUi(this);

    QMenu *fileMenu = new QMenu;
    fileMenu->addAction(QString::fromLocal8Bit("新建文件或项目"));
    fileMenu->addAction(QString::fromLocal8Bit("打开文件或项目"));
    fileMenu->addSeparator();
    fileMenu->addAction(QString::fromLocal8Bit("打开文件,用..."));
    fileMenu->addAction(QString::fromLocal8Bit("最近访问的文件"));
    fileMenu->addAction(QString::fromLocal8Bit("最近使用的项目"));
    QList<QAction*> Actions = fileMenu->actions();
    Actions.value(0)->setShortcut(QKeySequence::New);
    Actions.value(1)->setShortcut(QKeySequence::Open);
    Actions.value(2)->setShortcut(QKeySequence::Close);
    Actions.value(3)->setShortcut(QKeySequence::Copy);
    Actions.value(4)->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_F));

    QMenu *editMenu = new QMenu;
    editMenu->addAction("Undo");
    editMenu->addAction("Redo");
    editMenu->addSeparator();
    editMenu->addAction("Remove");
    editMenu->addAction("Delete");
    editMenu->addAction("Advanced");

    QMenuBar *bar = new QMenuBar(this);
    bar->addAction(new QAction(QString::fromLocal8Bit("文件")));
    bar->addAction(new QAction(QString::fromLocal8Bit("编辑")));
    bar->addAction(new QAction(QString::fromLocal8Bit("构建")));
    bar->addAction(new QAction(QString::fromLocal8Bit("调试")));
    bar->addAction(new QAction(QString::fromLocal8Bit("Analyze")));
    bar->addAction(new QAction(QString::fromLocal8Bit("工具")));
    bar->addAction(new QAction(QString::fromLocal8Bit("控件")));
    bar->addAction(new QAction(QString::fromLocal8Bit("帮助")));

    bar->actions().value(0)->setMenu(fileMenu);
    bar->actions().value(1)->setMenu(editMenu);

    bar->actions().value(0)->setShortcut(Qt::ALT + Qt::Key_N);
    bar->actions().value(1)->setShortcut(Qt::ALT + Qt::Key_E);


    connect(bar,&QMenuBar::triggered,this,[=](QAction *action){
        int index = bar->actions().indexOf(action);
        qDebug()<<mapToGlobal(bar->pos());
        if(index == 0){
            fileMenu->move(mapToGlobal(bar->pos()) + QPoint(0,bar->height()));
            fileMenu->show();
        }

        if(index == 1){
            editMenu->move(mapToGlobal(bar->pos()) + QPoint(43,bar->height()));
            editMenu->show();
        }
    });
    show();
}

menuWidget::~menuWidget()
{
    delete ui;
}

相关标签: # Qt-基本控件