How to make a MenuBar in Qt?

Create Folder mainwindow. Go inside this folder using

$cd mainwindow

Create 3 files in it. main.cpp, mainwindow.cpp and mainwindow.h

main.cpp

#include <QApplication>                                               

int main(int argc, char *argv[])                                      
{                                                                     
  // create main event loop handler and parse command line arguments  
  QApplication app(argc, argv);                                       

  // create application main window & enter main event loop           
  MainWindow window;                                                  
  window.setWindowTitle("QNotepad");
  window.show();                                                      
  return app.exec();                                                  
}

mainwindow.cpp

#include "mainwindow.h"

#include <QMenuBar>
#include <QStatusBar>

/******************************************************************/
/******** Main application window for QSimulate *******************/
/********************constructor **********************************/

MainWindow::MainWindow() : QMainWindow()
{
  // add drop down menus (currently empty)
  menuBar()->addMenu("&File");
  menuBar()->addMenu("&Edit");
  menuBar()->addMenu("&View");
  menuBar()->addMenu("&Insert");  
  menuBar()->addMenu("&Format");
  menuBar()->addMenu("&Help");

  // add status bar message
  statusBar()->showMessage("Notepad has started");
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

/******************************************************************/
/************ Main application window for QNotepad *****************/
/******************************************************************/

class MainWindow : public QMainWindow
{
public:
  MainWindow();                       // constructor
};

#endif  // MAINWINDOW_H

The #ifndef,  #define at the beginning of the file and #endif at the end of the file, is the standard C++ construction to avoid errors if a header file happens to be included more than once.

 MainWindow class is derived from QMainWindow to inherit the excellent Qt functionality. Initially we keep things very simple with only a constructor.

To compile the code

$cd mainwindow
$qmake -project
$qmake mainwindow.pro
$make
$./mainwindow

You will get a window like this:

qn1

Thats all

Advertisements

About Priyanka Kapoor

Simple, Hardworking & friendly.....
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s