Qt 教程 之 菜单简单使用

#ifndef MENU_H #define MENU_H #include<QMainWindow> class QMenu; class QAction; class QLabel; class QWidget; class MainWindow :public QMainWindow { Q_OBJECT private: QMenu *fileMenu; QMenu*editMenu; QAction *newAct; QAction *openAct; QAction*findAct; QLabel*infoLabel; private slots: void newFile(); void openFile(); void findFile(); public: MainWindow(); void createAction(); void createMenu(); }; #endif

#include<QMenu> #include<QAction> #include<QWidget> #include<QVBoxLayout> #include<QMenuBar> #include<QLabel> #include"menu.h" MainWindow::MainWindow(){ QWidget *widget=new QWidget(); setCentralWidget(widget); infoLabel=new QLabel("how are you?"); infoLabel->setAlignment(Qt::AlignCenter); QVBoxLayout *layout=new QVBoxLayout(); layout->addWidget(infoLabel); widget->setLayout(layout); createAction(); createMenu(); } void MainWindow::createAction(){ newAct=new QAction("&new",this); newAct->setShortcut(QKeySequence("Ctrl+N")); newAct->setStatusTip("new File"); connect(newAct,SIGNAL(triggered()),this,SLOT(newFile())); openAct=new QAction("&open",this); openAct->setShortcut(tr("ctrl+O")); openAct->setStatusTip("open File"); connect(openAct,SIGNAL(triggered()),this,SLOT(openFile())); findAct=new QAction("&find",this); findAct->setShortcut(tr("Ctrl+F")); findAct->setStatusTip("find"); connect(findAct,SIGNAL(triggered()),this,SLOT(findFile())); } void MainWindow::createMenu(){ fileMenu=menuBar()->addMenu("&File"); fileMenu->addAction(newAct); fileMenu->addAction(openAct); editMenu=menuBar()->addMenu("&Open"); editMenu->addAction(findAct); } void MainWindow::newFile(){ infoLabel->setText("create a new file"); } void MainWindow::openFile(){ infoLabel->setText("open a file"); } void MainWindow::findFile(){ infoLabel->setText("find a file"); }

#include<QApplication> #include"menu.h" int main(int argc, char *argv[]) { QApplication app(argc,argv); MainWindow mainWidnow; mainWidnow.show(); return app.exec(); }

你可能感兴趣的:(Qt 教程 之 菜单简单使用)