Qt之菜单栏工具栏入门

时间:2023-12-24 14:57:19

菜单栏基本操作

创建菜单栏

QMenuBar *menuBar = new QMenuBar(this); //1.创建菜单栏
menuBar->setGeometry(,,width(),); //设置大小 QMenu *fileMenu = new QMenu("File",this); //2.创建菜单
//3.创建行为(Action)
QAction *fileCreateAction = new QAction("create",this);
QAction *fileSaveAction = new QAction("save",this);
QAction *fileImportAction = new QAction("import",this);
QAction *fileExportAction = new QAction("export",this);
//4.将行为添加到菜单
fileMenu->addAction(fileSaveAction);
fileMenu->addAction(fileImportAction);
fileMenu->addAction(fileExportAction);
fileMenu->addAction(fileCreateAction);
//5.将菜单添加到菜单栏
menuBar->addMenu(fileMenu);

可以通过自定义槽函数实现想要的功能

//行为连接到具体的槽函数
connect(fileCreateAction,SIGNAL(triggered()),this,SLOT(createFile()));  //槽函数需要实现
connect(fileSaveAction,SIGNAL(triggered()),this,SLOT(saveFile()));
connect(fileImportAction,SIGNAL(triggered()),this,SLOT(importFile()));
connect(fileExportAction,SIGNAL(triggered()),this,SLOT(exportFile()));

为菜单再添加菜单实现多级菜单

QMenu *optionMenu = new QMenu("Option",this);   //创建菜单
QAction *optionSystemAction = new QAction("System",this);
QMenu *ComparisionMenu = new QMenu("Comparison",this);//**这里创建再一个菜单
QAction *optionFindEdgeAction = new QAction("Find edge",this);
QAction *optionSetDecimalAction = new QAction("Set decima",this);
optionMenu->addAction(optionSystemAction);
//添加二级菜单
optionMenu->addMenu(ComparisionMenu);//***
QAction *openAction = new QAction("open",this);
QAction *closeAction = new QAction("close",this);
//为二级菜单添加行为
ComparisionMenu->addAction(openAction);
ComparisionMenu->addAction(closeAction); optionMenu->addAction(optionFindEdgeAction);
optionMenu->addAction(optionSetDecimalAction);
menuBar->addMenu(optionMenu);

工具栏

//新建一个工具栏
QToolBar *toolBar = new QToolBar("toolbar",this);
//设置大小
toolBar->setGeometry(,,width(),); //新建行为(Action)
tAction1 = new QAction(QIcon(":/icon/icon/Vegetables-_11.png"),"Vegetables",this);
tAction2 = new QAction(QIcon(":/icon/icon/Vegetables-_12.png"),"Vegetables",this);
tAction3 = new QAction(QIcon(":/icon/icon/Vegetables-_13.png"),"Vegetables",this); //设置可选中,默认为false,triggered(bool)信号传递的bool永远为false
tAction1->setCheckable(true);
tAction2->setCheckable(true);
tAction3->setCheckable(true); //可以通过判断是否选中设置不同的样式
connect(tAction1,SIGNAL(triggered(bool)),this,SLOT(changeIcon(bool))); //添加行为
toolBar->addAction(tAction1);
toolBar->addAction(tAction2);
toolBar->addAction(tAction3);
void MainWindow::changeIcon(bool boolValue)
{
if(boolValue)
tAction1->setIcon(QIcon(":/icon/icon/Vegetables-_1.png"));
else
tAction1->setIcon(QIcon(":/icon/icon/Vegetables-_11.png"));
}