1. Trang chủ
  2. » Công Nghệ Thông Tin

KDE 2/Qt Programming Bible phần 3 pdf

74 191 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 74
Dung lượng 324 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The following example creates the window shown in Figure 6-4.This menu bar was contrived to demonstrate the different things you can use in the construction of a menu.. Figure 6-7: A men

Trang 1

Chapter 6 ✦ Menus and Toolbars

The method createStatusBar()on line 36 calls statusBar()to create andinstall a widget capable of displaying a single line of text Your program has access

to the text of the status bar, so it can keep it constantly updated Unlike the toolbarand the menu bar, the status bar cannot be moved to another location

The method createToolBar()on line 41 creates a toolbar by calling toolBar()

on line 43 An ID number is required as an argument because your application canhave as many toolbars as you would like You supply the ID number and, if there is

no toolbar with that ID, one is created and returned Using the same ID number willalways return the same toolbar For this example, a pixmap is used to create a sin-gle toolbar button

The toolbar can be moved outside of its parent window Figure 6-3 shows the result

of using the handle at the left end of the toolbar to “tear off” the menu from its ent window and establish it as its own stand-alone window

par-Figure 6-3: Tear-off menus and toolbars

The method named slotExit()on line 47 is called whenever the user selects Exitfrom the menu You may need to do some kind of cleanup here and save currentlyunsaved data, but this example simply calls the exit()method in the application

The global variable named kappalways contains a pointer to the KApplicationobject

The slot method named queryClose()on line 51 is called when the figure X in theupper right corner of the application’s frame is selected If this slot returns TRUE,the application is immediately closed If it returns FALSE, no action will be taken(the signal from the X button will be ignored)

This is the skeleton of an application Allowing KTMainWindowto do most of thework, your top-level window can be very sophisticated with only a few lines ofcode The rest of this chapter describes the details of configuring the menu bar and toolbars, and displaying information via the status bar

Trang 2

128 Part I ✦ Getting Started

The Menu Bar

Basically, a menu is a collection of buttons with a slot attached to each one Thedynamics of a menu simplifies access to the buttons by making a specific subset ofthem available at any one time There are different ways of organizing and decorat-ing the buttons The following example creates the window shown in Figure 6-4.This menu bar was contrived to demonstrate the different things you can use in the construction of a menu

Figure 6-4: An application

with a menu bar at the top

The header file mostly contains declarations of slots that will be called whenever amenu button is selected, but there is also some private data that is needed to trackthe status of menu buttons that are toggled from one state to another The MenuMainclass inherits from the KTMainWindowclass, so it already has the capability to dis-play and manage a menu

Trang 3

29 “This button is used as the top\n”

30 “level widget for this example It\n”

31 “is very safe to click the button\n”

32 “because it doesn’t do anything.\n”);

33 setView(button);

34 }

35 void MenuMain::createMenu()

36 {

Trang 4

130 Part I ✦ Getting Started

76 popup = new QPopupMenu();

77 popup2 = new QPopupMenu();

83 KHelpMenu *help = new KHelpMenu(this,

84 “Text that will appear in\n”

85 “a very simple About box”);

86 popup = help->menu();

Trang 5

The method createMenu()beginning on line 35 creates the menu bar and all of itsmembers There is one menu bar inside the KTMainWindowwidget, and its address

is retrieved and stored in the menubarpointer on line 37 Actually, the menu bardoes not exist until the menuBar()method is called, but subsequent menuBar()calls return the same menu bar pointer

Trang 6

132 Part I ✦ Getting Started

Each button appearing on the menu bar represents one QPopupMenuobject Thefirst one is created on line 42 and added to the menu bar on line 56 Between lines

42 and 56 a number of items are inserted in the pop-up menu, resulting in a menuthat looks like the one shown in Figure 6-5

Figure 6-5: A menu with icons

and accelerators

The call to insertItem()on line 56 specifies that the name of the menu be “File,”and the accelerator key be Alt-F That is, writing the label as “&File” instead of sim-ply “File” results in the letter being underlined when it is displayed; and pressingthe Alt-F key combination will cause the menu to appear, just as if you had selected

it with the mouse The up and down arrow keys can be used to locate a member ofthe menu; and the Return or Enter key will select it, just as if you had clicked it withthe mouse

The item labeled “New” is created with the call to insertItem()on line 43 Theaccelerator key is specified by the constant value ALT+Key_N This is a shortcut forselecting the menu item; whenever the application has the keyboard focus, typingALT-N produces the same result as selecting the New entry with the mouse Theaccelerator key appears on the right, as you can see in Figure 6-5 Notice that the

ampersand preceding the letter N causes it to be underlined; however, unlike the

menu bar, this does not automatically assign an accelerator key You can underline,

or not underline, as you choose The “Save As” selection has an accelerator key, butdoes not have a letter underlined

The accelerator keys are specified by special values that specify the key and itsmodifiers Three modifiers are available: ALT, CTRL, and SHIFT You can use none,one, two, or all three of them in combination with a key For example, the “Save As”entry defined on line 47 uses both the CTRL and SHIFT modifiers Many keys can

be used for accelerators The following list contains some of the more commonlyused keys

There are more keys defined than will appear on any one keyboard, but most of theones in this list are common enough that they should be useful, although I havenever seen a keyboard with 35 function keys If you have some special keys that youwould like to use, look in the source of the Qt header file named qnamespace.h,where you will find more than 230 keys listed

Trang 7

Chapter 6 ✦ Menus and Toolbars

Key_DeleteThe Close menu item defined on lines 49 through 52 is shown in Figure 6-5 with anicon displayed on its left To do this, the first step is to create a pixmap containingthe graphics This is done on line 49 by loading the data from the local disk filenamed flag.png The second step is to create a QIconSetobject from the pixmap,

as is done on line 50 The menu item itself is created by the call to insertItem()

on line 48, with the QIconSetinserted as the first argument; otherwise, the ments are the same as before

argu-Chapter 13, “Graphic Manipulation,” describes other ways to create pixmaps

To complete the File menu, line 53 inserts the horizontal separator line thatappears between Close and Exit Lines 54 and 55 create the Exit menu member

Figure 6-6 shows a menu with a pair of checkable buttons that can be toggled onand off The checkmark appears only when the button has been toggled on In thefigure, the Enable Colors button is on and the Enable Graphics button is off

Figure 6-6: A menu with toggle buttons

Cross-Reference

Trang 8

134 Part I ✦ Getting Started

The Toggles menu is created on line 58 and inserted into the menu bar on line 74.The call to setCheckable()on line 59 configures the pop-up menu so that all of its items can be toggled on and off This way, you can turn any item on the pop-upmenu into a toggled item simply by toggling it on and off

The actual toggling is not automatic The two slots for the toggle buttons — on lines

97 through 110 — check the current state of the toggle by calling isItemCheck(),and then call setItemChecked()to toggle it to the other state Because of thearguments required to toggle buttons in the slot methods, it was necessary to store

a pointer to the pop-up menu, along with the ID numbers of the two buttons, onlines 16 through 18 of the header file The ID numbers are the return values fromitemInsert(), on lines 60 and 63, and are the only way you can address a specificitem inside a pop-up menu

Instead of text, you can decorate your menus with pixmaps Figure 6-7 shows amenu using pixmaps for buttons They work just like the text menu buttons, so theycan have accelerator keys and be toggle buttons In the figure, you can see that onepixmap is larger than the other — it is up to you to size your pixmaps, because eachmenu item will expand to accommodate whatever you give to it

Figure 6-7: A menu using

pixmaps for buttons

The pop-up menu with the pixmaps is created on lines 70 through 74 Notice thatthe same QPixmapobject is used for both of the buttons — this works because theinsertItem()method makes its own local copy The only difference between apixmap and a text button is the type of the first argument — on lines 71 and 73, aQPixmapobject reference is the first argument

A submenu can be created by inserting one pop-up menu into another as one of itsitems Lines 76 through 81 create a second pop-up menu, named popup2, and insert

it into its parent menu with the label “Orientation ” The resulting menu, whenselected, looks like the one shown in Figure 6-8

Figure 6-8: A menu with a submenu

Trang 9

Chapter 6 ✦ Menus and Toolbars

The KHelpMenuobject is created on line 80 and installed as the rightmost member

of the menu bar on lines 86 and 87 The resulting menu is shown in Figure 6-9

Figure 6-9: The layout of the standard

In this example, the call to the static method QWhatsThison line 24 inserts theexplanatory text into the button used as the main window Making the selectionfrom the menu changes the cursor to a question mark that, when used to select anitem, will display the text The text is displayed in a window with a simple borderand a yellow background, as shown in Figure 6-10

Figure 6-10: Text displayed as a

response to “What’s this?”

The two bottom buttons on the menu are the About boxes The default About boxfor the application is a simple block of text with an OK button, and there is a stan-dard About box with information about the current version of KDE

You can use KHelpMenuand replace the built-in About box with one of your own To

do this, extend the KHelpMenuclass and include a slot named aboutApplication().Instead of popping up the default About box, this slot will be executed — and you cancreate your own About box and display it

Trang 10

136 Part I ✦ Getting Started

You can find some examples of creating About boxes in Chapter 5

Pop-up Menus

A QPopupMenuobject does not need to be connected to a QMenuBar A menu can bepopped up in the middle of a widget All your application has to do is specify thelocation and call the show()method The following example responds to the rightmouse button by displaying a pop-up menu, as shown in Figure 6-11

Figure 6-11: A menu pops up from

the middle of a widget

On line 7, the class MenuPopupuses QWidgetas its base class And, because it is

a widget, it inherits the virtual protected method mousePressEvent(), which

is called whenever the mouse pointer is within the widget and a mouse button ispressed

Cross-Reference

Trang 11

up the menu Lines 21 through 26 insert the items into the menu.

The virtual method mousePressedEvent()on line 29 overrides the one in the ent QWidgetclass The method is called whenever a mouse button is clicked Thetest on line 31 determines whether the right mouse button is the one selected; if so,the call to move()positions the menu and the call to exec()pops it up The coor-dinate position, supplied to the call to move()on line 32, is the sum of the x and

par-y coordinates of the parent widget and those of the mouse pointer The resulting

coordinate is the location of the mouse on the screen, causing the menu to appeardirectly beneath the mouse

Trang 12

138 Part I ✦ Getting Started

The Toolbar

KTMainWindowwill manage as many toolbars as you care to insert into it By default,they will appear at the top of the window in the order that you insert them If there isalso a menu, the toolbars will appear beneath it And you can have more things in atoolbar than just button icons The following example, shown in Figure 6-12, installstwo toolbars containing buttons, separators, a combo box, and even a label widget

Figure 6-12: A pair of toolbars

containing several items

on line 17 is used by the system to ask your application for permission to close it

Trang 14

140 Part I ✦ Getting Started

80 void ToolbarMain::slotFont(int index) {}

The ToolbarMainconstructor, beginning on line 15, calls methods to create a widget for the main window and a pair of toolbars The main widget created in the method createMainWidget()found on line 21 is simply a pushbutton.Toolbar number one (the top toolbar) is created in the method createToolBarOne()on line 27 As shown previously in Figure 6-12, each member of this toolbarhas its own pixmap The pixmaps are loaded from files on lines 29 through 33 TheKToolBaris created by calling the method toolBar()that this class inheritedfrom KTMainWindow Unlike the menu creation method described earlier, thetoolBar()method creates and returns a new toolbar every time you call it Andthe toolbar it returns to you has already been inserted into KTMainWindowas part

of the display

There is a small space between the third and fourth members of the top toolbar.This space is inserted by the call to insertSeparator()on line 42 If you want awider space, you can insert more separators

Trang 15

Chapter 6 ✦ Menus and Toolbars

The second toolbar, created by the method createToolBarTwo()on line 48, tains more than simple toolbar buttons A normal toolbar button is added by thecall to insertButton()on line 52; and just to its right, a vertical line separator isinserted with the call to insertLineSeparator()on line 55

con-An array of strings is inserted into a QStrListobject with calls to insert()on lines

58 through 60, and the array is used to install a combo box in the toolbar by callinginsertCombo()on line 61 Internally, KToolBarcreates a standard QComboBoxtomanage the list, so most of the information passed to insertCombo()is passed on tothe QComboBox The insert()methods on lines 58 through 60 define the combo boxtext, and assign an ID number to each one The call to insertCombo()on line 61specifies that the list be used to create the QComboBox, that it has an ID number of 11,and that it is not writeable by the user The signal is activated()and the slot isslotFont(), and they both have an intargument so that the ID number of the selection can be passed to the slot method The TRUEargument specifies that theQComboBoxis to be enabled The string “Select Font” specifies the text of the tooltip,and the number 110 specifies the width in pixels

The combo box in this example calls the slot with the ID number, but it is possible

to use the character string instead To do this, use the method activated(String &)as the signal, and slotFont(String &) as the slot

You can install any widget into a toolbar If, for example, you want to have morecontrol over the QComboBoxthan you would have by calling insertCombo(), youcan create your own combo box and install it by calling insertWidget() The code

on lines 68 and 69 creates and installs a label Notice that the label doesn’t respond

to the mouse the way the other items do When you are installing a widget, the bar assumes you have set up all of the signals and slots you will need to get yourresponses

tool-The Status Bar

There is an optional KStatusBarwidget included as part of KTMainWindow It isnormally displayed at the bottom of the window, and it can be used by your appli-cation to display, and continuously update, a line of text The following example,shown in Figure 6-13, uses a status bar to display the current value of an internalcounter that is incremented and decremented by a pair of buttons

Figure 6-13: A status bar tracking a value

Note

Trang 16

142 Part I ✦ Getting Started

Trang 18

144 Part I ✦ Getting Started

The method createMainWidget()beginning on line 20 uses a KContainerLayoutwidget to hold the two buttons, as shown previously in Figure 6-13 One button isconnected to the slot method slotAddOne()and the other is connected toslotSubtractOne()

The status bar itself is initialized in the method createStatusBar()on line 39.The call to statusBar()instantiates the status bar and returns a pointer to it.Because there can only be one KStatusBarin a KTMainWindow, subsequent calls

to statusBar()will return the address of the same status bar object In fact, if youare only going to need access to the status bar from inside this class, there is noneed to save the pointer yourself because it can always be retrieved

Lines 42 and 43 call the insertItem()method of the status bar to insert the played string The string is inserted in two parts (there can be more), and each one

dis-is assigned an ID number The strings will each be ddis-isplayed in the order in whichyou add them, and the ID numbers are needed if you wish to change them This way,you can change part of the string without the necessity of changing all of it Forexample, the slot method slotAddOne()on line 45 is called whenever the “Add”button is selected, causing the counter to be incremented; and the status bar textwith ID number 2 is replaced by the call to changeItem() The text with the ID num-ber 1 is not changed Similarly, the “Subtract” button executes slotSubtractOne()

on line 50, which decrements the counter and changes only the text of ID number 2.The arg() methods of the QString class are used to format various data typesinto strings Examples of all the data types, and the formatting options, aredescribed in Chapter 16, which discusses some of the utility classes

You can break the displayed string into as many text segments (or, if you prefer,text items) as you wish, and work with each one individually You can also call theKStatusBarmethod clear()to remove the text from all the ID numbers

Summary

The KTMainWindowclass is a special top-level window containing code that can beused to supply the user with access to the facilities of the application, and to keepthe user informed of the application’s current status

✦ A menu bar can be displayed at either the top or bottom of the top-level dow At the user’s discretion, it can be torn off the top-level window andappear as a separate entity on the screen

win-✦ Any window can have a menu pop up under control of the mouse or board Making a selection from this menu, or clicking the mouse on anotherlocation, will remove the menu from the display

key-Note

Trang 19

Chapter 6 ✦ Menus and Toolbars

✦ A number of toolbars can be individually positioned on any of the four sides

of the top-level window, or each one can be torn off to appear as an dent item on the screen

indepen-✦ A status bar, with constantly updated text, can be made to appear at the tom of the top-level window

bot-Chapter 7 describes widgets that can be used to create and display related tions, such as a group of radio buttons that can all interact with one another so thatonly one of them can be selected at any one time, or a combo box that allows theuser to select one or more items from a list

Trang 21

Grouping Widgets

This chapter examines several of the widgets and

contain-ers that can be used to solve some of the problems thatoften arise when windows are being laid out For example,

it is possible to create a single widget that holds a set of buttons, and to have all these buttons attached to the sameslot There is a need to relate radio buttons to one anotherbecause selecting one of them causes the others in the group

to become deselected Sometimes groups of widgets arerelated by the function they perform, and there is a way

to draw a frame around them so you can indicate this to the user

KButtonBox

It is very common to have a row of buttons across the bottom

of a dialog window The class KButtonBoxis a container get that simplifies the task of positioning the row of buttons

wid-The following example uses a KButtonBoxto manage threebuttons arranged horizontally:

11

12 KButtonBox *box =

13 newKButtonBox(0,KButtonBox::HORIZONTAL,25,15);

a single slotInterlinking a set

of radio buttonsRelating a set ofcheck buttonsEnabling the framesbuilt into somewidgetsDecorating yourwidgets with framesSliding separatorbars to resizemultiple widgets

Trang 22

148 Part I ✦ Getting Started

14 button1 = box->addButton(“First Button”);

15 button2 = box->addButton(“Second Button”);

16 button3 = box->addButton(“Third Button”);

is the row of buttons shown in Figure 7-1

Figure 7-1: Three buttons contained in a

KButtonBox

The calls to addButton()on lines 14 through 16 create the buttons — that is, theKButtonBoxcreates each button and returns a pointer to it To keep the examplesimple, the buttons are not connected to slots The call to layout()on line 17 isnecessary because it tells the KButtonBoxthat you are not going to be adding any-thing else and that it should go ahead and configure itself Lines 18 and 19 are thesame as for any other widget — the KButtonBoxis instructed to display itself (and,thus, all its contents); and it is sized in such a way that it assumes its minimumheight and width

The buttons in Figure 7-1 are all the same size If you would rather have the width

of the buttons vary according to the length of the text they contain, you can specifythis as the second argument to the addButton()method For example, the follow-ing code causes the buttons to vary in width according to the text they contain:button1 = box->addButton(“First Button”,TRUE);

button2 = box->addButton(“Second Button”,TRUE);

button3 = box->addButton(“Third Button”,TRUE);

Making this second argument FALSE(the default) will cause KButtonBoxto mine the size of the widest button and resize the others to match it

Trang 23

Chapter 7 ✦ Grouping Widgets

Rarely does the width of the KButtonBoxmatch exactly the width of the dialog thatcontains it, so you may want to specify how and where it stretches itself to fit Thelayout at the top of Figure 7-2 shows the default stretch, with all the buttons on the left The layout at the bottom of the figure shows what happens if you specify

a stretch point

Figure 7-2: A KButtonBox with and without stretch defined

To do this, insert the stretch point between two buttons as follows:

button1 = box->addButton(“First Button”);

button2 = box->addButton(“Second Button”);

box->addStretch(1)button3 = box->addButton(“Third Button”);

The stretching is done the same as it is for the containers discussed in Chapter 3

That is, you can add as many stretch points as you like; and each one will stretch

in proportion to the others — the proportions are determined by the value of theargument in addStretch()

With a single change, the previous example can be converted to a vertical orientation

Change the second argument on the constructor to VERTICAL:KButtonBox *box =

new KButtonBox(0,KButtonBox::VERTICAL,25,15);

The resulting window is shown in Figure 7-3 The space separating the buttons fromthe edges and from one another are specified in the same way When the window isstretched vertically, the KButtonBoxwill simply insert space at the bottom, or atwhatever locations you specify for stretching

Figure 7-3: A KButtonBox with vertical orientation

Trang 24

150 Part I ✦ Getting Started

Grouping Buttons with a Single Slot

A QButtonGroupobject can be used to organize a group of buttons either tally or vertically Each button added to the group is assigned an ID number andyou can, if you wish, use a single slot method for all of the buttons While you cancreate a QButtonGroupdirectly, it is simpler to use either a QHButtonGroupor aQVButtonGroup, depending on whether you want the buttons to be arranged hori-zontally or vertically A QButtonGroupis also a QFrame, so you can use the QFramemethod calls to change the appearance of the grouping

horizon-The following example contains four buttons inside a horizontal QButtonGroup.Beneath the row of buttons, as shown in Figure 7-4, is a label that has its textupdated as each button is pushed

Figure 7-4: The QHButtonGroup

widget organizes buttons horizontally

of the buttons so the slot method can determine which button was clicked

Trang 25

23 QHButtonGroup *group = new QHButtonGroup(this,”hg1”);

24 button = new QPushButton(“Set Color”,group);

Trang 26

152 Part I ✦ Getting Started

The QHButtonGroupis created on line 23 using the HorizPushobject as its parentwidget, because although the QVBoxLayoutobject acts as a container, it is not

a widget The HorizPushobject inherits QWidget, so it can act as the parent ofanother widget

Lines 24 through 31 create the four pushbuttons and insert them into theQHButtonGroup Because a QHButtonGroupis also a widget, it can act as the parent of the pushbutton widgets The calls to insert()assign an ID number toeach button as it inserts it into the group If you do not specify ID numbers, the first button will default to 0, the second to 1, and so on However, because these IDnumbers are the only way you will have to identify the buttons, it is a good idea tospecify them yourself In this example, the values are declared as values in an enu-merated type, which should make it a simple matter to add or remove buttons

On line 32, a call to connect()attaches the checked()signal of the QHButtonGroup

to the local slot named slotButton() On line 34, the QHButtonGroupis insertedinto the top of the vertical box On lines 36 and 37, a label is created and stored in the bottom of the vertical box

Internally, the QHButtonGrouphas a slot that receives the clicked()signals fromeach of the buttons It then issues its own clicked()signal, which carries the IDnumber assigned to the button The slot named slotButton()on line 42 receivesthe signal and uses the IDnumber to determine what action is to be taken If the ID

is equal to SetColoror Configure, the text is set accordingly If the IDis equal toClear, the text is cleared An Exitvalue will cause the program to exit

Whereas a QHButtonGroupwidget can be used to display buttons horizontally,

a QVButtonGroupcan be used to display them vertically The process required isexactly the same as the one used to create the horizontal grouping To change theprevious example so it displays the window shown in Figure 7-5, change line 4 toinclude the vertical button group instead of the horizontal button group:

Trang 27

Chapter 7 ✦ Grouping Widgets

Figure 7-5: The QVButtonGroup widget

organizes buttons vertically

Grouping Radio Buttons

A QVButtonGroupcan be used to handle the relationship among a vertical set ofradio buttons, and a QHButtonGroupcan be used to control a horizontal set When-ever a QRadioButtonis inserted into a QButtonGroup, it becomes related to theother buttons in such a way that only one can be selected The window shown inFigure 7-6 is produced by the following example

Figure 7-6: The QVButtonGroup widget

controls a set of radio buttons

15 enum ButtonChoice { Total, Average,

16 Maximum, Minimum, Exit };

Trang 28

154 Part I ✦ Getting Started

Each button has a unique ID number, and the values in the enumeration ButtonChoicedefined on line 15 enable your program to refer to each number by a name.VertRadio

24 QVButtonGroup *group = new QVButtonGroup(this,”vg1”);

25 button = new QRadioButton(“Total”,group);

Trang 29

Lines 24 through 32 create four radio buttons and insert them into the QVButtonGroup A normal QPushButtonis created on line 33 and installed in the sameQVButtonGroupwidget on line 34 To create the buttons, the QVButtonGroup

is used as the parent widget All radio buttons in QButtonGroupautomaticallybecome related so that only one at a time will be selected You can mix the types

of buttons in the group because the QVButtonGrouprelates radio buttons only —any other kinds of buttons will remain independent entities

The slot method slotButton()defined on line 45 is called for all of the buttons, nomatter what their type Examining the value of the button ID, the slot method setsthe text of the label to indicate which radio button is currently on The nonradiobutton can be used to exit the program

While it usually makes more sense to organize radio buttons vertically, if you findyourself in a situation in which you need to arrange them horizontally, it can be donevery easily The result of converting the previous example to a horizontal orientation

is shown in Figure 7-7 To make the conversion, change line 5 to the following:

#include <qhbuttongroup.h>

And change line 24 to the creation of a horizontal group box:

QHButtonGroup *group = new QHButtonGroup(this,”hg1”);

Figure 7-7: A group of radio buttons

organized horizontally

Trang 30

156 Part I ✦ Getting Started

Grouping Check Buttons

A QCheckBoxis a button that can be toggled between off and on states The state is

maintained inside the QCheckBoxitself A check button is sometimes referred to as a

toggle button The following example creates the collection of check buttons shown in

Figure 7-8 The checkmark only appears if a check button is in the on state.

Figure 7-8: A group of QCheckBox buttons organized vertically

17 enum ButtonChoice { Total, Average,

18 Maximum, Minimum, Exit };

Trang 31

Chapter 7 ✦ Grouping Widgets

The QVButtonGroupis included as part of the class data, on line 15, because the slotthat receives button information only supplies the button ID number, making it nec-essary to query the groupfor the check button status The current QCheckButtonstatus settings are stored in the Boolean variables defined on lines 19 through 22

23 group = new QVButtonGroup(this,”vg1”);

24 button = new QCheckBox(“Total”,group);

Trang 32

158 Part I ✦ Getting Started

Lines 24 through 31 create the four QCheckBoxobjects and insert them into theQVButtonGroup A fifth button — a standard pushbutton — is created and insertedinto groupon lines 32 through 35 On lines 38 and 39, a label used to display thetext at the bottom of the window is created and installed into the layout.The default condition of a QCheckBoxis off, which is represented as FALSE, so lines

41 through 44 are used to set the four internal flags to the same values as the check

Trang 33

Chapter 7 ✦ Grouping Widgets

boxes If you wish to preset one or more of the check boxes to being initially on, it

could be done like this:

The switchstatement on line 52 is used to determine which button has beenselected If the button is a check box, a call to isChecked()returns TRUEif the

button is on and FALSEif it is off Storing the check box state in a local Boolean

variable gives the program quick access to the state of all the buttons

If the value of IDindicates that it is the Exit button, the casestatement on line 65executes, causing a call to exit()to halt the application

Lines 68 through 77 create a string specifying which of the toggles are currently on,

and set the string as the text of the label displayed at the bottom of the windowshown earlier in Figure 7-8

Usually, groups of toggle buttons are arranged vertically, but there may be tions where you would like to arrange them horizontally The previous example can

situa-be reorganized to configure itself horizontally, as shown in Figure 7-9, by changingline7 of vertcheck.hto the following:

Figure 7-9: A group of QCheckBox

buttons organized horizontally

Trang 34

160 Part I ✦ Getting Started

Some Widgets Are Also Frames

If you need to enclose a collection of widgets in a frame or box to indicate that thewidgets are somehow related, act as a unit, or should otherwise be set apart fromother widgets in the same window, a QFramewidget can be used to enclose them in

a box Even when no widgets are left outside the QFrameenclosure, the decorativelook of the frame can improve the overall appearance of a window

In the inheritance tree, the immediate base class of QFrameis QWidget This meansthat any widget you construct can be decorated by simply using QFrameinstead ofQWidgetas the base class And many of the existing widgets are already constructedthis way For example, the QLabelwidget uses QFrameas its base class but defaults

to having the decorations turned off — adding a frame to a label is simply a matter ofspecifying the type and size The following example displays the window shown inFigure 7-10, which shows four labels with their frames enabled

Figure 7-10: Four labels with their frames enabled

Trang 35

Chapter 7 ✦ Grouping Widgets

21 QVBoxLayout *layout = new QVBoxLayout(this,8);

Lines 23 through 29 create a label that uses a combination of the Boxshape with theshadowing set to Sunken The resulting shadow pattern makes the box look as if itwere engraved into the surface The lineWidth()method on line 25 specifies thepixel width of each of the two lines that make up the edges of the trough in the cen-ter The setMidLine()method on line 26 specifies the width of the trough in thecenter of the line The calls to setAlignment()and setMargin()on lines 27 and 28center the text and put an eight-pixel boundary between the text and the frame

Lines 31 through 37 create another label with the Boxshape, but this time it usesthe Raisedshadowing This causes the box to appear as if it were a ridge stickingout of the surface The lines drawn for this frame are narrower than those drawn forthe previous one because the call to setLineWidth()on line 33 specifies that theedges of the ridge be only one pixel wide

Trang 36

162 Part I ✦ Getting Started

Lines 39 through 43 create a label with the style WinPanel, which is to be owed such that it appears to be raised The width is allowed to default, and there

shad-is no midline width because there shad-is no trough or ridge

Lines 45 through 50 create a label with the style Panel, which is shadowed to makethe entire label appear to be sunken into the surface Each line drawn around theedge is four pixels wide, because of the call to setLineWidth()on line 48

Many of the Qt and KDE widgets use QFrameas a base class Some of them display aframe by default, but they are all capable of displaying a frame With any of the fol-lowing widgets, a call to the method setFrameStyle()causes a frame to appear:

Trang 37

Chapter 7 ✦ Grouping Widgets

Framing Options

You can use a number of settings to specify the appearance of a frame: Box, Panel,WinPanel, Hline, or Vline Moreover, each of these styles can be set to appearraised, sunken, or plain And the widths of the lines can be specified The followingexamples demonstrate the different ways in which a frame can be configured

The Box QFrame

The program named boxframedisplays the different appearances of a Boxtype offrame The three possible adjustments are the line width, the midline width, andwhether the appearance should be sunken, plain, or raised Figure 7-11 shows theappearance of the frames with line widths varying from 1 to 3, and midline widthsvarying from 0 to 2

Figure 7-11: Twenty-seven different appearances of the Box

QFrame type

The following program is used to generate the set of frames shown in Figure 7-11 Ituses a grid layout to position all the frames and labels, and has a loop that createsand inserts the frames with different settings

Ngày đăng: 13/08/2014, 22:21