Mac下的菜单通常的显示在顶部,其中菜单混合有系统相关的菜单选项,下面介绍下Qt Mac添加菜单的方式
添加菜单
直接上代码:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMenuBar>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
auto menuBar = new QMenuBar;
this->setMenuBar(menuBar);
//不启用原生菜单
// menuBar->setNativeMenuBar(false);
auto *fileMenu = menuBar->addMenu("File");
fileMenu->addAction("Open File");
auto *helpMenu = menuBar->addMenu("Help");
//about会自动添加到主菜单
// helpMenu->addAction("About");
// helpMenu->addAction("About Qt");
helpMenu->addAction("Help");
auto quitAction = new QAction("Quit");
//重载系统退出菜单,能够触发相关的信号
quitAction->setMenuRole(QAction::QuitRole);
connect(quitAction, &QAction::triggered, this, [=](bool checked){
qDebug() << __FUNCTION__ << "song" << checked;
});
helpMenu->addAction(quitAction);
auto perAction = new QAction("Preferences");
//主菜单固定有一项Preferences,快捷键为command+,
perAction->setMenuRole(QAction::PreferencesRole);
helpMenu->addAction(perAction);
auto specificAction = new QAction("Specific1");
//重要的菜单,也会添加到主菜单
specificAction->setMenuRole(QAction::ApplicationSpecificRole);
helpMenu->addAction(specificAction);
auto aboutAction = new QAction;
//关于菜单,固定位置,且文字为about+程序名
aboutAction->setMenuRole(QAction::AboutRole);
helpMenu->addAction(aboutAction);
auto aboutDefAction = new QAction("about software");
//关于菜单,可自定义文案
aboutDefAction->setMenuRole(QAction::AboutQtRole);
helpMenu->addAction(aboutDefAction);
auto textHeuristicAction = new QAction("TextHeuristic");
// textHeuristicAction->setMenuRole(QAction::TextHeuristicRole);
helpMenu->addAction(textHeuristicAction);
// setUnifiedTitleAndToolBarOnMac(true);
}
MainWindow::~MainWindow()
{
delete ui;
}
效果:
系统菜单通过QMenuBar进行添加,使用menuBar->setNativeMenuBar(false);就不会添加到顶部的菜单栏,和Windows一样在主窗口上。
默认直接添加是添加新的菜单,如代码中的file 和 help,Mac的程序默认都会有一个以应用程序为名称的菜单项,我们姑且称为主菜单吧,如果想在主菜单添加菜单项,可以通过MenuRole进行设置,代码中已做了说明,可自行尝试
enum MenuRole { NoRole = 0, TextHeuristicRole, ApplicationSpecificRole, AboutQtRole,
AboutRole, PreferencesRole, QuitRole };
翻译菜单
主菜单中有几项是系统自带的菜单项,这几项默认是没有翻译的,需要另外提供翻译
翻译文件我已经准备好了,下载地址:QtMac系统菜单翻译的ts文件-C++文档类资源-CSDN下载
使用Qt的翻译工具生成对应的.qm文件,使用QTranslator加载即可