17.17 WINDOWS WITH MENUS IN Qt


17.17 WINDOWS WITH MENUS IN Qt

To convey the basics of how menus and menu items are specified in Qt, we will now show a Qt implementation of the example of the previous section. Our top-level window, an object of type WindowWithMenu, will be equipped with a menu bar and will contain a text area of type QMultiLineEdit for entering and editing text as in the previous example. Since there are two very different ways of specifying an action for a menu item in Qt, this time we will incorporate two separate menus in the menu bar to illustrate the two different ways. Now the menu bar will include, as before, a File menu consisting of the usual items-New, Open, Save-and a Color menu, consisting of four different colors. When a user selects an item from the Color menu, the border of the text area would change to that color.

In the program below, the header file for the WindowWithMenu class declares two functions, load() and save(), in lines (B) and (C). These are, respectively, for loading into the text area the contents of a disk file and saving the contents of the text area into a disk file. The slots defined in lines (D) through (G) are:

      void allowTextEntry();      void getTextFromFile();      void saveTextToFile();      void selectColor(int); 

The first three of the slot functions are for the three items of the File menu. And the last for the four color items of the Color menu. Note that whereas we provide a separate slot function for each item of the File menu, we provide only one slot function for all the four items of the Color menu. Actually, as we will show in greater detail later, we get multiple uses from the single slot function for the Color menu by virtue of providing it with an int parameter. Selecting each item from the Color menu will invoke selectColor( int ) with a different argument.

Looking at the data members of the WindowWithMenu class

      QMultiLineEdit* textarea;      QMenuBar* menubar;      QPopupMenu* filemenu;      QPopupMenu* colormenu;      const QColor* borderColor; 

the first two are the two different components of the top-level window, the menubar at the top of the window and the text area. Then come the two menus. Finally, we have a variable for the color of the border of the text area.

We are now ready to show how menus are created in Qt. We have basically two choices, the first exemplified by how we create filemenu, and the second by how we create colormenu. In either case, we start out by creating a QPopupMenu object:

      filemenu = new QPopupMenu(this);        ...        ...      colormenu = new QPopupMenu(this); 

where the argument, this, establishes the parent-child relationship of the menu item (so that when the parent is destroyed, the child will be also). The program creates these two objects in lines (H) and (J).

For the filemenu case, we insert items into the menu by statements of the kind

      filemenu->insertItem("New", this, SLOT(allowTextEntry())); 

as shown in line (I). In the statement in line (I), the first argument, "New", is the character string that will be displayed for the menu item, and the second argument declares the object that will supply the slot function for handling the signal emitted by selecting this menu item. Finally, the last argument is for naming the slot function.

The second approach to specifying a menu item is exemplified by the following group of statements for the Color menu in lines (K) through (L) of the program:

      colormenu->insertItem("blue", BLUE);      colormenu->insertItem("yellow", YELLOW);      colormenu->insertItem("magenta", MAGENTA);      QObject::connect(colormenu,                     SIGNAL(activated(int)),                     this,                     SLOT(selectColor(int))); 

where the symbolic constants BLUE, YELLOW, and MAGENTA are defined in the enumeration in line (A) of the header file WindowWithMenu.h. In this manner, we are associating with each menu item an integer that in the example here is supplied by the enumeration definition. When a user clicks on one of these menu items, the signal activated(int) will be issued, with the parameter set to the integer value associated with the menu item. As to which function gets to trap this signal, that is supplied by the connect invocation above. So if the user clicks on the item "blue", the signal activated(0) will be invoked, causing the invocation of selectColor(0).

In lines (M) through (O), we insert the menus thus constructed into the menu bar, and at the same time give names to the menus, by the following statements:

      menubar = new QMenuBar(this);      menubar->insertItem("&File", filemenu);      menubar->insertItem("Color", colormenu); 

Attaching an & to the name of the menu, as we have done for the menu "File," means that we can associate a keyboard accelerator with this menu.

The rest of the program is self-explanatory. The executable can be built by

      make -f Makefile_Qt_WindowWithMenu 

and, if needed, the binaries can be cleaned up by

      make -f Makefile_Qt_WindowWithMenu clean 

 
////////////////////// file: WindowWithMenu.h ////////////////////// #ifndef WINDOWWITHMENU_H #define WINDOWWITHMENU_H #include <qmultilineedit.h> #include <qmenubar.h> #include <qpopupmenu.h> #include <qcolor.h> #include <qtextstream.h> #include <qstatusbar.h> enum BackgroundColor { //(A) BLUE, YELLOW, MAGENTA }; class WindowWithMenu: public QWidget { Q_OBJECT public: WindowWithMenu(QWidget *parent=0, const char* name= 0); ~WindowWithMenu(); void load(const char *fileName); //(B) void save(const char *fileName); //(C) public slots: void allowTextEntry(); //(D) void getTextFromFile(); //(E) void saveTextToFile(); //(F) void selectColor(int); //(G) private: QMultiLineEdit* textarea; QMenuBar* menubar; QPopupMenu* filemenu; QPopupMenu* colormenu; const QColor* borderColor; }; #endif ////////////////////// file: WindowWithMenu.cc ////////////////////// #include "WindowWithMenu.h" #include <qfiledialog.h> #include <iostream> WindowWithMenu::WindowWithMenu(QWidget* parent, const char* name) : QWidge (parent, name) { setPalette(QPalette(QColor(250, 250, 200))); filemenu = new QPopupMenu(this); //(H) filemenu->insertItem("New", this, SLOT(allowTextEntry())); //(I) filemenu->insertItem("Open", this, SLOT(getTextFromFile())); filemenu->insertItem("Save", this, SLOT(saveTextToFile())); colormenu = new QPopupMenu(this); //(J) colormenu->insertItem("blue", BLUE); //(K) colormenu->insertItem("yellow", YELLOW); colormenu->insertItem("magenta", MAGENTA); QObject::connect(colormenu, //(L) SIGNAL(activated(int)), this, SLOT(selectColor(int))); menubar = new QMenuBar(this); //(M) menubar->insertItem("&File", filemenu); //(N) menubar->insertItem("Color", colormenu); //(O) QRect rect = menubar->frameGeometry(); int h = rect.height(); textarea = new QMultiLineEdit(this); textarea->setGeometry(0, h, 300, 350); textarea->setReadOnly(TRUE); } WindowWithMenu::~WindowWithMenu() {} void WindowWithMenu::allowTextEntry() { cout << "New selected" << endl; textarea->setReadOnly( FALSE ); } void WindowWithMenu::getTextFromFile() { QFileDialog* fd = new QFileDialog(); QString fileName = fd->getOpenFileName(QString::null, QString::null, this); cout << "file selected: " + fileName << endl; if (!fileName.isEmpty() && !fileName.isNull()) load(fileName); else cout << "File is either empty or does not exist" << endl; } void WindowWithMenu::saveTextToFile() { QString fileName = QFileDialog::getSaveFileName (QString::null, QString::null, this); save(fileName); } void WindowWithMenu::selectColor(int item) { switch(item) { case BLUE: borderColor = &blue; // predefined QColor object textarea->setPalette(QPalette( *borderColor)); textarea->repaint(); break; case YELLOW: borderColor = &yellow; textarea->setPalette(QPalette(*borderColor)); textarea->repaint(); break; case MAGENTA: borderColor = &magenta; textarea->setPalette(QPalette(*borderColor)); textarea->repaint(); break; default: borderColor = &white; textarea->setPalette(QPalette(*borderColor)); textarea->repaint(); } } void WindowWithMenu::load(const char* fileName) { QFile f(fileName); if (!f.open(IO_ReadOnly)) return; textarea->setAutoUpdate(FALSE); QTextStream t(&f); while (!t.eof()) { QString s = t.readLine(); textarea->append(s); } f.close(); textarea->setAutoUpdate(TRUE); textarea->repaint(); textarea->setEdited(FALSE); textarea->setReadOnly(FALSE); } void WindowWithMenu::save (const char* filename) { QString text = textarea->text(); QFile f(filename); if(!f.open(IO_WriteOnly)) { cout << "Could not write to the file" << endl; return; } QTextStream t(&f); t << text; f.close(); textarea->setEdited(FALSE); } /////////////////// file: main_WindowWithMenu.cc /////////////////// #include <qapplication.h> #include "WindowWithMenu.h" int main(int argc, char ** argv) { QApplication a(argc, argv); WindowWithMenu* m = new WindowWithMenu(); m->setGeometry(100, 200, 400, 400); m->setCaption("Window with Menu"); a.setMainWidget(m); m->show(); a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit())); return a.exec(); } ////////////////// file: Makefile_Qt_WindowWithMenu ////////////////// CC=g++ LDLIBS=-L$(QTDIR)/lib -lqt CFLAGS=-g -I$(QTDIR)/include WindowWithMenu: moc_WindowWithMenu.o WindowWithMenu.o \ main_WindowWithMenu.o Makefile_Qt_WindowWithMenu $(CC) $(LDLIBS) -o WindowWithMenu moc_WindowWithMenu.o WindowWithMenu.o main_WindowWithMenu.o moc_WindowWithMenu.cc: WindowWithMenu.h moc -o moc_WindowWithMenu.cc WindowWithMenu.h moc_WindowWithMenu.o: moc_WindowWithMenu.cc $(CC) -c $(CFLAGS) -02 moc_WindowWithMenu.cc WindowWithMenu.o: WindowWithMenu.cc $(CC) -c $(CFLAGS) -02 WindowWithMenu.cc main_WindowWithMenu.o: main_WindowWithMenu.cc $(CC) -c $(CFLAGS) -02 main_WindowWithMenu.cc clean: rm -f WindowWithMenu rm -f moc*.* rm -f *.o

The GUI for this program looks like what is shown in Figure 17.32. The screen shot for the figure was taken with the pull-down "File" menu visible.

click to expand
Figure 17.32




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net