qt代码增加菜单动作按键

转载自:https://blog.csdn.net/yao_hou/article/details/80769560 (未修改)
Qt添加菜单有两种方法,一是用代码直接手动添加,二是在Qtdesigner中在界面上直接添加。
先介绍用代码如何添加。
需要用到两个类QMenu和QAction,例如我的Demo程序界面如下:
在这里插入图片描述

对于“新建”,“编辑”这些主菜单项用QMenu, 而"文件"下面的子菜单,“新建”,“打开”我们称为QAction,

例如新建一个【文件】主菜单项,

QMenu *fileMenu;
fileMenu = menuBar()->addMenu(QString::fromLocal8Bit("文件"));

添加三个子菜单,先new三个QAction的对象

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

然后用addAction()方法,将子菜单添加到主菜单项,QMenu是继承于QWidget, addAction()是QWidget的成员方法。

void addAction(QAction *action);
在点击子菜单项时要响应动作,会触发 triggered() 信号,每一个动作我们需要手动链接该信号,例如:

connect(myAc2, SIGNAL(triggered()), this, SLOT(pop2()));
菜单还可以设置快捷键,状态信息,工具栏快捷方式等。下面直接贴出代码,比较简单。我的项目名称是:Caidan, 开发环境VS2015 + Qt5.7

头文件

#pragma once
 
#include <QtWidgets/QMainWindow>
#include "ui_Caidan.h"
#include <QAction>
 
class Caidan : public QMainWindow
{
	Q_OBJECT
 
public:
	Caidan(QWidget *parent = Q_NULLPTR);
 
private slots:
	void pop1();
	void pop2();
	void pop3();
 
private:
	Ui::CaidanClass ui;
	QMenu *fileMenu;
	QMenu *editMenu;
 
	QAction *myAc1;
	QAction *myAc2;
	QAction *myAc3;
};

.cpp文件

#include "Caidan.h"
#include <QMessageBox>
 
Caidan::Caidan(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	
	myAc1 = new QAction(this);
	myAc1->setText(QString::fromLocal8

Bit("新建"));
	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 Caidan::pop1()
{
	QMessageBox m(this);
	m.setWindowTitle("MyAction1");
	m.setText("This is a messagebox for my action1.");
	m.exec();
}
 
void Caidan::pop2()
{
	QMessageBox m(this);
	m.setWindowTitle("MyAction2");
	m.setText("This is a messagebox for my action2.");
	m.exec();
}
 
void Caidan::pop3()
{
	QMessageBox m(this);
	m.setWindowTitle("MyAction3");
	m.setText("This is a messagebox for my action3.");
	m.exec();
}

猜你喜欢

转载自blog.csdn.net/weixin_40385285/article/details/86076098