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

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

#ifndef GWDEMO_H
#define GWDEMO_H

#include 
#include 
#include 

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 

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);
}

你可能感兴趣的:(Qt)