Qt添加菜单栏

两种方法,一是用代码直接手动添加,二是在Qtdesigner中在界面上直接添加。

这里介绍用代码如何添加,需要用到两个类QMenu和QAction,Demo程序界面如下:

Qt添加菜单栏_第1张图片

QtGuiApplication4.cpp

#include "QtGuiApplication4.h"
#include 
#include 

QtGuiApplication4::QtGuiApplication4(QWidget *parent)
  : QMainWindow(parent)
{
  ui.setupUi(this);
  myAc1 = new QAction(this);  
  myAc1->setText(QString::fromLocal8Bit("新建"));
  myAc1->setStatusTip("This is ac1.");      
  //myAc1->setShortcuts(QKeySequence::Print); //设置快捷方式  
  myAc1->setShortcut(QKeySequence("Ctrl+8")); //随意指定快捷方式  
  ui.mainToolBar->addAction(myAc1);          //工具条  
  connect(myAc1, SIGNAL(triggered()), this, SLOT(pop1()));   
  myAc2 = new QAction(this);  
  myAc2->setText(QString::fromLocal8Bit("打开"));  
  myAc2->setStatusTip("This is ac2");  
  connect(myAc2, SIGNAL(triggered()), this, SLOT(pop2()));   
  myAc3 = new QAction(this);  
  myAc3->setText(QString::fromLocal8Bit("另存为"));  
  myAc3->setStatusTip("This is ac3");  
  connect(myAc3, SIGNAL(triggered()), this, SLOT(pop3()));   
  fileMenu = menuBar()->addMenu(QString::fromLocal8Bit("文件"));  
  fileMenu->addAction(myAc1);  
  fileMenu->addAction(myAc2);  
  fileMenu->addAction(myAc3);   
  editMenu = menuBar()->addMenu(QString::fromLocal8Bit("编辑"));

}
void QtGuiApplication4::pop1()
{
  QMessageBox m(this);  
  m.setWindowTitle("MyAction1");  
  m.setText("This is a messagebox for my action1.");  
  m.exec();
} 
void QtGuiApplication4::pop2()
{ 
  QMessageBox m(this);  
  m.setWindowTitle("MyAction2");  
  m.setText("This is a messagebox for my action2.");  
  m.exec(); 
} 
void QtGuiApplication4::pop3()
{ 
  QMessageBox m(this);  
  m.setWindowTitle("MyAction3");  
  m.setText("This is a messagebox for my action3.");  
  m.exec(); 
}

QtGuiApplication4.h

#pragma once

#include 
#include "ui_QtGuiApplication4.h"
#include 

class QtGuiApplication4 : public QMainWindow
{
  Q_OBJECT

public:
  QtGuiApplication4(QWidget *parent = Q_NULLPTR);

private:
  Ui::QtGuiApplication4Class ui;
  QMenu *fileMenu;
  QMenu *editMenu;

  QAction *myAc1;
  QAction *myAc2;
  QAction *myAc3;

private slots:
  void pop1();
  void pop2();
  void pop3();
};

参考

  1. Qt 添加菜单及菜单的事件
  2. Qt添加菜单栏和工具栏

你可能感兴趣的:(qt)