Qt 添加菜单及菜单的事件响应(完整的示例)

2020-08-19 11:11:19 浏览数 (1)

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

先介绍用代码如何添加。

需要用到两个类QMenu和QAction,例如我的Demo程序界面如下:

QtGuiApplication4.cpp

代码语言:javascript复制
#include "QtGuiApplication4.h"
#include <qpushbutton.h>
#include <QMessageBox>

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

代码语言:javascript复制
#pragma once

#include <QtWidgets/QMainWindow>
#include "ui_QtGuiApplication4.h"
#include <QAction>

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();
};
代码语言:javascript复制
在VS2010中建立Qt工程但是代码中总是出现红色波浪线。解决办法
qt

0 人点赞