【Qt】菜单栏、工具栏、状态栏、右键菜单的实现

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u010168781/article/details/84572130

在QMainWidget基础上实现菜单栏、工具栏、状态栏、右键菜单。
头文件:

#ifndef GWDEMO_H
#define GWDEMO_H

#include <QMainWindow>
#include <QMenu>
#include <QAction>

namespace Ui {
class GWDemo;
}

class GWDemo : public QMainWindow
{
	Q_OBJECT

public:
	explicit GWDemo(QWidget *parent = 0);
	~GWDemo();
private slots:
	void slotActionNew();
	void slotContextMenu(QPoint pos);//右键菜单,也叫上下文菜单

private:
	void init();
	void createActions();
	void createMenus();
	void createToolBar();

private:
	Ui::GWDemo *ui;
	QMenu *m_pMenuFile;
	QAction *m_pActionNew;
	QToolBar *m_pToolBarFile;
};
#endif // GWDEMO_H

实现文件

#include "GWDemo.h"
#include "ui_GWDemo.h"

#include <QDebug>

GWDemo::GWDemo(QWidget *parent) :
	QMainWindow(parent),
	ui(new Ui::GWDemo)
{
	ui->setupUi(this);
	init();
	createActions();
	createMenus();
	createToolBar();
}

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

void GWDemo::slotActionNew()
{
	qDebug() << "new action";
}

void GWDemo::slotContextMenu(QPoint pos)
{
	qDebug() << "centext Menu";
	QMenu menu(this);
	menu.addAction(m_pActionNew);
	menu.exec(mapToGlobal(pos));
}

void GWDemo::init()
{
	//触发右键菜单
	this->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotContextMenu(QPoint)));
}

void GWDemo::createActions()
{
	m_pActionNew = new QAction("&New", this);
	m_pActionNew->setIcon(QIcon(":/ico/ico/new.png"));
	m_pActionNew->setShortcut(QKeySequence::New);//设置快捷键
	m_pActionNew->setStatusTip("Create a new file");//在状态栏显示
	m_pActionNew->setShortcutVisibleInContextMenu(true);
	connect(m_pActionNew, SIGNAL(triggered(bool)), this, SLOT(slotActionNew()));
}

void GWDemo::createMenus()
{
	m_pMenuFile = menuBar()->addMenu("&File");//方便键盘操作:Alt+F来选中
	m_pMenuFile->addAction(m_pActionNew);
}

void GWDemo::createToolBar()
{
	m_pToolBarFile = addToolBar("&File");
	m_pToolBarFile->addAction(m_pActionNew);
}
展开阅读全文

没有更多推荐了,返回首页