qt之菜单的使用

     


       首先从QMainWindow 中派生一个类,名为QMain,然后在构造函数中创建菜单,,每个菜单都有QAction组成,而这些QAction中,可以设置图标,快捷键,当被选中时在状态栏显示的文字,当然最重要的是用connect将QAction的triggered信号和相应的槽连接起来。

  下面是代码

    qmain.h

       

      

#ifndef QMAIN_H
#define QMAIN_H
 
  
#include 
#include 
class QMain : public QMainWindow
{
    Q_OBJECT
public:
    explicit QMain(QWidget *parent = 0);
protected:
    void  createAction();
    void createMenu();
    void createToolBar();
 
  
signals:
 
  
public slots:
 
  
private:
    QAction* exitAction;
    QAction* openAction;
    QAction* addNoteAction;
    QAction* cutAction;
    QAction* copyAction;
    QAction* pasteAction;
    QMenu* fileMenu;
    QMenu* editMenu;
};
 
  
#endif // QMAIN_H
qmain.cpp
     
#include "qmain.h"
#include 
#include 
#include 
QMain::QMain(QWidget *parent) : QMainWindow(parent)
{
    createAction();
    createMenu();
   resize(500,600);
}
void  QMain::createAction()
{
    exitAction = new QAction(tr("E&xit"),this);
    exitAction->setIcon(QIcon(":/images/delete.png"));
    exitAction->setShortcut(tr("Ctrl+Q"));
    connect(exitAction,SIGNAL(triggered(bool)),this,SLOT(close()));
    openAction = new QAction("&Open",this);
    openAction->setShortcut(QKeySequence::Open);
    openAction->setStatusTip(tr("open"));
   addNoteAction = new QAction(tr("node"),this);
   addNoteAction->setIcon(QIcon(tr(":/images/node.png")));
   addNoteAction->setStatusTip(tr("add node"));
 
  
    cutAction = new  QAction(tr("&Cut"),this);
    cutAction->setIcon(QIcon(tr(":/images/cut.png")));
    cutAction->setShortcut(QKeySequence::Cut);
    cutAction->setStatusTip(tr("cut Text"));
     copyAction = new QAction(tr("&Copy"),this);
     copyAction->setIcon(QIcon(tr(":/images/copy.png")));
     copyAction->setShortcut(QKeySequence::Copy);
 
  
     pasteAction = new QAction(tr("&Paste"),this);
     pasteAction->setIcon(QIcon(":/images/paste.png"));
     pasteAction->setShortcut(QKeySequence::Paste);
     pasteAction->setStatusTip(tr("paste text"));
}
 
  
void QMain::createMenu()
{
 fileMenu = menuBar()->addMenu("&File");
 fileMenu->addAction(exitAction);
 
  
 editMenu = menuBar()->addMenu("&Edit");
editMenu->addAction(addNoteAction);
editMenu->addAction(cutAction);
editMenu->addAction(pasteAction);
editMenu->addAction(openAction);
}
 
  
void QMain::createToolBar()
{
 
  
}
 
  
main.cpp:
 
  
    

#include 
#include 


int main(int argc,char* argv[])
{
    QApplication app(argc,argv);
    QMain* ma = new QMain;
    ma->show();
    return app.exec();
}
    
 
  
 
  
 
  

你可能感兴趣的:(qt之菜单的使用)