菜單欄基本操作
創建菜單欄
QMenuBar *menuBar = new QMenuBar(this); //1.創建菜單欄 menuBar->setGeometry(0,0,width(),40); //設置大小 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(0,40,width(),40); //新建行為(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")); }