方法一:《C++ GUI programming with Qt 4, Second Edition》给出的一种方法:QMenum定义单个菜单,调用menuBar()函数创建菜单栏,再往菜单栏里添加子菜单、Action或其他dialog.
.h
QMenu *file;
QMenu *edite;
QMenu *help;
QMenu *submenu;
QMenuBar *menubar;
QMenuBar *my_menubar;
QAction *openfile;
QAction *createfile;
QAction*recentfiles;
.cpp
openfile = new QAction(tr("&open"), this);
createfile = new QAction(tr("&newfile"), this);
recentfiles = new QAction(tr("&recentfiles"), this);
file = menuBar()->addMenu(tr("&file"));//QMainWindow::menuBar()返回一个QMenuBar的指针,第一次调用这个函数就会创建菜单栏
submenu = file->addMenu(tr("&submenu")); //添加子菜单
submenu->addAction(openfile); //菜单里添加动作
file->addAction(openfile);
file->addAction(createfile);
file->addAction(recentfiles);
edite = menuBar()->addMenu(tr("&edite"));
help = menuBar()->addMenu(tr("&help"));
方法二:
Qt中的弹出式菜单用类 QPopupMenu表示,每一个菜单需要编写代码逐个加入。
QPopupMenu* file = new QPopupMenu;
file->insertItem("&Open", this, SLOT( openFile() ) );
file->insertItem("&Save", this, SLOT( saveFile() ) );
file->insertSeparator();
file->insertItem("&Quit", this, SLOT( exitMain() ) );
第一句构造出一个弹出式菜单的实例,后面使用insertItem分别添加四条菜单项目。insertItem有多种使用形式,上面是最常用的也是最简单的一种。第一个参数表示菜单文本,第二个和第三个参数表示接受菜单事件的类和slot。需要注意的是insertItem()方法的第2,3个参数,这实际上是调用了connect()方法把菜单被选择这个事件和某个类的Slot()方法连接起来,这是很典型的用法。
方法三:
Qt参考文档给出了一个综合性的方法,调用QMenuBar::insertItem()函数,其第二个参数是指向QPopupMenu类的指针
Example of creating a menu bar with menu items (from menu/menu.cpp):
QPopupMenu*file = newQPopupMenu(this );
file->insertItem(p1, "&Open", this,SLOT(open()), CTRL+Key_O );
file->insertItem(p2, "&New", this, SLOT(news()), CTRL+Key_N );
menu = new QMenuBar( this );
menu->insertItem("&File", file );
In most main window style applications you would use themenuBar() provided inQMainWindow,addingQPopupMenusto the menu bar and addingQActionsto the popup menus.
Example (from action/application.cpp):
QPopupMenu* file = newQPopupMenu(this );
menuBar()->insertItem("&File", file );
fileNewAction->addTo(file );