~oif-team/ubuntu/natty/qt4-x11/xi2.1

« back to all changes in this revision

Viewing changes to doc/html/widgets-imageviewer.html

  • Committer: Bazaar Package Importer
  • Author(s): Adam Conrad
  • Date: 2005-08-24 04:09:09 UTC
  • Revision ID: james.westby@ubuntu.com-20050824040909-xmxe9jfr4a0w5671
Tags: upstream-4.0.0
ImportĀ upstreamĀ versionĀ 4.0.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<?xml version="1.0" encoding="iso-8859-1"?>
 
2
<!DOCTYPE html
 
3
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
 
4
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 
5
<!-- /tmp/qt-4.0.0-espenr-1119621036935/qt-x11-opensource-desktop-4.0.0/doc/src/examples/imageviewer.qdoc -->
 
6
<head>
 
7
    <title>Qt 4.0: ImageViewer Example</title>
 
8
    <style>h3.fn,span.fn { margin-left: 1cm; text-indent: -1cm; }
 
9
a:link { color: #004faf; text-decoration: none }
 
10
a:visited { color: #672967; text-decoration: none }
 
11
td.postheader { font-family: sans-serif }
 
12
tr.address { font-family: sans-serif }
 
13
body { background: #ffffff; color: black; }</style>
 
14
</head>
 
15
<body>
 
16
<table border="0" cellpadding="0" cellspacing="0" width="100%">
 
17
<tr>
 
18
<td align="left" valign="top" width="32"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></td>
 
19
<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="mainclasses.html"><font color="#004faf">Main&nbsp;Classes</font></a>&nbsp;&middot; <a href="annotated.html"><font color="#004faf">Annotated</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped&nbsp;Classes</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td>
 
20
<td align="right" valign="top" width="230"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></td></tr></table><h1 align="center">ImageViewer Example</h1>
 
21
<p>Files:</p>
 
22
<ul>
 
23
<li><a href="widgets-imageviewer-imageviewer-cpp.html">widgets/imageviewer/imageviewer.cpp</a></li>
 
24
<li><a href="widgets-imageviewer-imageviewer-h.html">widgets/imageviewer/imageviewer.h</a></li>
 
25
<li><a href="widgets-imageviewer-main-cpp.html">widgets/imageviewer/main.cpp</a></li>
 
26
</ul>
 
27
<p>The example shows how to combine <a href="qlabel.html">QLabel</a> and <a href="qscrollarea.html">QScrollArea</a> to display an image. <a href="qlabel.html">QLabel</a> is typically used for displaying text, but it can also display an image. <a href="qscrollarea.html">QScrollArea</a> provides a scrolling view around another widget. If the child widget exceeds the size of the frame, <a href="qscrollarea.html">QScrollArea</a> automatically provides scroll bars.</p>
 
28
<p>The example demonstrates how <a href="qlabel.html">QLabel</a>'s ability to scale its contents (<a href="qlabel.html#scaledContents-prop">QLabel::scaledContents</a>), and <a href="qscrollarea.html">QScrollArea</a>'s ability to automatically resize its contents (<a href="qscrollarea.html#widgetResizable-prop">QScrollArea::widgetResizable</a>), can be used to implement zooming and scaling features. In addition the example shows how to use <a href="qpainter.html">QPainter</a> to print an image.</p>
 
29
<center><img src="images/imageviewer-example.png" alt="Screenshot of the ImageViewer example" /></center><p>With the <tt>ImageViewer</tt> application, the users can view an image of their choice. The <b>File</b> menu gives the user the possibility to:</p>
 
30
<ul>
 
31
<li><b>Open...</b> - Open an image file</li>
 
32
<li><b>Print...</b> - Print an image</li>
 
33
<li><b>Exit</b> - Exit the application</li>
 
34
</ul>
 
35
<p>Once an image is loaded, the <b>View</b> menu allows the users to:</p>
 
36
<ul>
 
37
<li><b>Zoom In</b> - Scale the image up by 25%</li>
 
38
<li><b>Zoom Out</b> - Scale the image down by 25%</li>
 
39
<li><b>Normal Size</b> - Show the image at its original size</li>
 
40
<li><b>Fit to Window</b> - Stretch the image to occupy the entire window</li>
 
41
</ul>
 
42
<p>In addition the <b>Help</b> menu provides the users with information about the ImageViewer example in particular, and about Qt in general.</p>
 
43
<a name="imageviewer-class-definition"></a>
 
44
<h2>ImageViewer Class Definition</h2>
 
45
<pre>&nbsp;   class ImageViewer : public QMainWindow
 
46
    {
 
47
        Q_OBJECT
 
48
 
 
49
    public:
 
50
        ImageViewer();
 
51
 
 
52
    private slots:
 
53
        void open();
 
54
        void print();
 
55
        void zoomIn();
 
56
        void zoomOut();
 
57
        void normalSize();
 
58
        void fitToWindow();
 
59
        void about();
 
60
 
 
61
    private:
 
62
        void createActions();
 
63
        void createMenus();
 
64
        void updateActions();
 
65
        void scaleImage(double factor);
 
66
        void adjustScrollBar(QScrollBar *scrollBar, double factor);
 
67
 
 
68
        QLabel *imageLabel;
 
69
        QScrollArea *scrollArea;
 
70
        double scaleFactor;
 
71
 
 
72
        QPrinter printer;
 
73
 
 
74
        QAction *openAct;
 
75
        QAction *printAct;
 
76
        QAction *exitAct;
 
77
        QAction *zoomInAct;
 
78
        QAction *zoomOutAct;
 
79
        QAction *normalSizeAct;
 
80
        QAction *fitToWindowAct;
 
81
        QAction *aboutAct;
 
82
        QAction *aboutQtAct;
 
83
 
 
84
        QMenu *fileMenu;
 
85
        QMenu *viewMenu;
 
86
        QMenu *helpMenu;
 
87
    };</pre>
 
88
<p>The <tt>ImageViewer</tt> class inherits from <a href="qmainwindow.html">QMainWindow</a>. We reimplement the constructor, and create several private slots to facilitate the menu entries. In addition we create four private functions.</p>
 
89
<p>We use <tt>createActions()</tt> and <tt>createMenus()</tt> when constructing the <tt>ImageViewer</tt> widget. We use the <tt>updateActions()</tt> function to update the menu entries when a new image is loaded, or when the <b>Fit to Window</b> option is toggled. The zoom slots use <tt>scaleImage()</tt> to perform the zooming. In turn, <tt>scaleImage()</tt> uses <tt>adjustScrollBar()</tt> to preserve the focal point after scaling an image.</p>
 
90
<a name="imageviewer-class-implementation"></a>
 
91
<h2>ImageViewer Class Implementation</h2>
 
92
<pre>&nbsp;   ImageViewer::ImageViewer()
 
93
    {
 
94
        imageLabel = new QLabel;
 
95
        imageLabel-&gt;setBackgroundRole(QPalette::Base);
 
96
        imageLabel-&gt;setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
 
97
        imageLabel-&gt;setScaledContents(true);
 
98
 
 
99
        scrollArea = new QScrollArea;
 
100
        scrollArea-&gt;setBackgroundRole(QPalette::Dark);
 
101
        scrollArea-&gt;setWidget(imageLabel);
 
102
        setCentralWidget(scrollArea);
 
103
 
 
104
        createActions();
 
105
        createMenus();
 
106
 
 
107
        setWindowTitle(tr(&quot;Image Viewer&quot;));
 
108
        resize(500, 400);
 
109
    }</pre>
 
110
<p>In the constructor we first create the label and the scroll area.</p>
 
111
<p>We set <tt>imageLabel</tt>'s size policy to <a href="qsizepolicy.html#Policy-enum">ignored</a>, making the users able to scale the image to whatever size they want when the <b>Fit to Window</b> option is turned on. Otherwise, the default size polizy (<a href="qsizepolicy.html#Policy-enum">preferred</a>) will make scroll bars appear when the scroll area becomes smaller than the label's minimum size hint.</p>
 
112
<p>We ensure that the label will scale its contents to fill all available space, to enable the image to scale properly when zooming. If we omitted to set the <tt>imageLabel</tt>'s <a href="qlabel.html#scaledContents-prop">scaledContents</a> property, zooming in would enlarge the <a href="qlabel.html">QLabel</a>, but leave the pixmap at its original size, exposing the <a href="qlabel.html">QLabel</a>'s background.</p>
 
113
<p>We make <tt>imageLabel</tt> the scroll area's child widget, and we make <tt>scrollArea</tt> the central widget of the <a href="qmainwindow.html">QMainWindow</a>. At the end we create the associated actions and menus, and customize the <tt>ImageViewer</tt>'s appearance.</p>
 
114
<pre>&nbsp;   void ImageViewer::open()
 
115
    {
 
116
        QString fileName = QFileDialog::getOpenFileName(this,
 
117
                                        tr(&quot;Open File&quot;), QDir::currentPath());
 
118
        if (!fileName.isEmpty()) {
 
119
            QImage image(fileName);
 
120
            if (image.isNull()) {
 
121
                QMessageBox::information(this, tr(&quot;Image Viewer&quot;),
 
122
                                         tr(&quot;Cannot load %1.&quot;).arg(fileName));
 
123
                return;
 
124
            }</pre>
 
125
<p>In the <tt>open()</tt> slot, we show a file dialog to the user. The easiest way to create a <a href="qfiledialog.html">QFileDialog</a> is to use the static convenience functions. <a href="qfiledialog.html#getOpenFileName">QFileDialog::getOpenFileName</a>() returns an existing file selected by the user. If the user presses <b>Cancel</b>, <a href="qfiledialog.html">QFileDialog</a> returns an empty string.</p>
 
126
<p>Unless the file name is a empty string, we check if the file's format is an image format by constructing a <a href="qimage.html">QImage</a> which tries to load the image from the file. If the constructor returns a null image, we use a <a href="qmessagebox.html">QMessageBox</a> to alert the user.</p>
 
127
<p>The <a href="qmessagebox.html">QMessageBox</a> class provides a modal dialog with a short message, an icon, and some buttons. As with <a href="qfiledialog.html">QFileDialog</a> the easiest way to create a <a href="qmessagebox.html">QMessageBox</a> is to use its static convenience functions. <a href="qmessagebox.html">QMessageBox</a> provides a range of different messages arranged along two axes: severity (question, information, warning and critical) and complexity (the number of necessary response buttons). In this particular example an information message with an <b>OK</b> button (the default) is sufficient, since the message is part of a normal operation.</p>
 
128
<pre>&nbsp;           imageLabel-&gt;setPixmap(QPixmap::fromImage(image));
 
129
            scaleFactor = 1.0;
 
130
 
 
131
            printAct-&gt;setEnabled(true);
 
132
            fitToWindowAct-&gt;setEnabled(true);
 
133
            updateActions();
 
134
 
 
135
            if (!fitToWindowAct-&gt;isChecked())
 
136
                imageLabel-&gt;adjustSize();
 
137
        }
 
138
    }</pre>
 
139
<p>If the format is supported, we display the image in <tt>imageLabel</tt> by setting the label's <a href="qlabel.html#pixmap-prop">pixmap</a>. Then we enable the <b>Print</b> and <b>Fit to Window</b> menu entries and update the rest of the view menu entries. The <b>Open</b> and <b>Exit</b> entries are enabled by default.</p>
 
140
<p>If the <b>Fit to Window</b> option is turned off, the <a href="qscrollarea.html#widgetResizable-prop">QScrollArea::widgetResizable</a> property is <tt>false</tt> and is it is our responsibility (not <a href="qscrollarea.html">QScrollArea</a>'s) to give the <a href="qlabel.html">QLabel</a> a reasonable size based on its contents. We call {<a href="qwidget.html#adjustSize">QWidget::adjustSize</a>()}{adjustSize()} to achieve this, which is essentially the same as</p>
 
141
<pre>&nbsp;   imageLabel-&gt;resize(imageLabel-&gt;pixmap()-&gt;size());
 
142
    void ImageViewer::print()
 
143
    {
 
144
        Q_ASSERT(imageLabel-&gt;pixmap());</pre>
 
145
<p>In the <tt>print()</tt> slot, we first make sure that an image has been loaded into the application. If the application is built in debug mode, the <tt>Q_ASSERT()</tt> macro will expand to</p>
 
146
<pre>&nbsp;   if (!imageLabel-&gt;pixmap())
 
147
         qFatal(&quot;ASSERT: &quot;imageLabel-&gt;pixmap()&quot; in file ...&quot;);</pre>
 
148
<p>In release mode, the macro simply disappear. The mode can be set in the application's <tt>.pro</tt> file. One way to do so is to add an option to <b>qmake</b> when building the appliction:</p>
 
149
<pre>&nbsp;   qmake &quot;CONFIG += debug&quot; foo.pro</pre>
 
150
<p>or</p>
 
151
<pre>&nbsp;   qmake &quot;CONFIG += release&quot; foo.pro</pre>
 
152
<p>Another approach is to add this line directly to the <tt>.pro</tt> file.</p>
 
153
<pre>&nbsp;       QPrintDialog dialog(&amp;printer, this);
 
154
        if (dialog.exec()) {
 
155
            QPainter painter(&amp;printer);
 
156
            QRect rect = painter.viewport();
 
157
            QSize size = imageLabel-&gt;pixmap()-&gt;size();
 
158
            size.scale(rect.size(), Qt::KeepAspectRatio);
 
159
            painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
 
160
            painter.setWindow(imageLabel-&gt;pixmap()-&gt;rect());
 
161
            painter.drawPixmap(0, 0, *imageLabel-&gt;pixmap());
 
162
        }
 
163
    }</pre>
 
164
<p>Then we present a print dialog allowing the user to choose a printer and to set a few options. We construct a painter with a <a href="qprinter.html">QPrinter</a> as the paint device. We set the painter's window and viewport in such a way that the image is as large as possible on the paper, but without altering its <a href="qt.html#AspectRatioMode-enum">aspect ratio</a>.</p>
 
165
<p>In the end we draw the pixmap at position (0, 0).</p>
 
166
<pre>&nbsp;   void ImageViewer::zoomIn()
 
167
    {
 
168
        scaleImage(1.25);
 
169
    }
 
170
 
 
171
    void ImageViewer::zoomOut()
 
172
    {
 
173
        scaleImage(0.8);
 
174
    }</pre>
 
175
<p>We implement the zooming slots using the private <tt>scaleImage()</tt> function. We set the scaling factors to 1.25 and 0.8, respectively. These factor values ensure that a <b>Zoom In</b> action and a <b>Zoom Out</b> action will cancel each other (since 1.25 * 0.8 == 1), and in that way the normal image size can be restored using the zooming features.</p>
 
176
<p>The screenshots below show an image in its normal size, and the same image after zooming in:</p>
 
177
<table align="center" cellpadding="2" cellspacing="1" border="0">
 
178
<tr valign="top" bgcolor="#f0f0f0"><td><img src="images/imageviewer-original_size.png" /></td><td><img src="images/imageviewer-zoom_in_1.png" /></td><td><img src="images/imageviewer-zoom_in_2.png" /></td></tr>
 
179
</table>
 
180
<pre>&nbsp;   void ImageViewer::normalSize()
 
181
    {
 
182
        imageLabel-&gt;adjustSize();
 
183
        scaleFactor = 1.0;
 
184
    }</pre>
 
185
<p>When zooming, we use the <a href="qlabel.html">QLabel</a>'s ability to scale its contents. Such scaling doesn't change the actual size hint of the contents. And since the <a href="qwidget.html#adjustSize">adjustSize()</a> function use those size hint, the only thing we need to do to restore the normal size of the currently displayed image is to call <tt>adjustSize()</tt> and reset the scale factor to 1.0.</p>
 
186
<pre>&nbsp;   void ImageViewer::fitToWindow()
 
187
    {
 
188
        bool fitToWindow = fitToWindowAct-&gt;isChecked();
 
189
        scrollArea-&gt;setWidgetResizable(fitToWindow);
 
190
        if (!fitToWindow)
 
191
            imageLabel-&gt;adjustSize();
 
192
 
 
193
        updateActions();
 
194
    }</pre>
 
195
<p>The <tt>fitToWindow()</tt> slot is called each time the user toggled the <b>Fit to Window</b> option. If the slot is called to turn on the option, we tell the scroll area to resize its child widget with the <a href="qscrollarea.html#widgetResizable-prop">QScrollArea::setWidgetResizable</a>() function. Then we disable the <b>Zoom In</b>, <b>Zoom Out</b> and <b>Normal Size</b> menu entries using the private <tt>updateActions()</tt> function.</p>
 
196
<p>If the <a href="qscrollarea.html#widgetResizable-prop">QScrollArea::widgetResizable</a> property is set to <tt>false</tt> (the default), the scroll area honors the size of its child widget. If this property is set to <tt>true</tt>, the scroll area will automatically resize the widget in order to avoid scroll bars where they can be avoided, or to take advantage of extra space. But the scroll area will honor the minimum size hint of its child widget independent of the widget resizable property. So in this example we set <tt>imageLabel</tt>'s size policy to <a href="qsizepolicy.html#Policy-enum">ignored</a> in the constructor, to avoid that scroll bars appear when the scroll area becomes smaller than the label's minimum size hint.</p>
 
197
<p>The screenshots below shows an image in its normal size, and the same image with the <b>Fit to window</b> option turned on. Enlarging the window will stretch the image further, as shown in the third screenshot.</p>
 
198
<table align="center" cellpadding="2" cellspacing="1" border="0">
 
199
<tr valign="top" bgcolor="#f0f0f0"><td><img src="images/imageviewer-original_size.png" /></td><td><img src="images/imageviewer-fit_to_window_1.png" /></td><td><img src="images/imageviewer-fit_to_window_2.png" /></td></tr>
 
200
</table>
 
201
<p>If the slot is called to turn off the option, the {QScrollArea::setWidgetResizable} property is set to <tt>false</tt>. We also restore the image pixmap to its normal size by adjusting the label's size to its content. And in the end we update the view menu entries.</p>
 
202
<pre>&nbsp;   void ImageViewer::about()
 
203
    {
 
204
        QMessageBox::about(this, tr(&quot;About Image Viewer&quot;),
 
205
                tr(&quot;&lt;p&gt;The &lt;b&gt;Image Viewer&lt;/b&gt; example shows how to combine QLabel &quot;
 
206
                   &quot;and QScrollArea to display an image. QLabel is typically used &quot;
 
207
                   &quot;for displaying a text, but it can also display an image. &quot;
 
208
                   &quot;QScrollArea provides a scrolling view around another widget. &quot;
 
209
                   &quot;If the child widget exceeds the size of the frame, QScrollArea &quot;
 
210
                   &quot;automatically provides scroll bars. &lt;/p&gt;&lt;p&gt;The example &quot;
 
211
                   &quot;demonstrates how QLabel's ability to scale its contents &quot;
 
212
                   &quot;(QLabel::scaledContents), and QScrollArea's ability to &quot;
 
213
                   &quot;automatically resize its contents &quot;
 
214
                   &quot;(QScrollArea::widgetResizable), can be used to implement &quot;
 
215
                   &quot;zooming and scaling features. &lt;/p&gt;&lt;p&gt;In addition the example &quot;
 
216
                   &quot;shows how to use QPainter to print an image.&lt;/p&gt;&quot;));
 
217
    }</pre>
 
218
<p>We implement the <tt>about()</tt> slot to create a message box describing what the example is designed to show.</p>
 
219
<pre>&nbsp;   void ImageViewer::createActions()
 
220
    {
 
221
        openAct = new QAction(tr(&quot;&amp;Open...&quot;), this);
 
222
        openAct-&gt;setShortcut(tr(&quot;Ctrl+O&quot;));
 
223
        connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
 
224
 
 
225
        printAct = new QAction(tr(&quot;&amp;Print...&quot;), this);
 
226
        printAct-&gt;setShortcut(tr(&quot;Ctrl+P&quot;));
 
227
        printAct-&gt;setEnabled(false);
 
228
        connect(printAct, SIGNAL(triggered()), this, SLOT(print()));
 
229
 
 
230
        exitAct = new QAction(tr(&quot;E&amp;xit&quot;), this);
 
231
        exitAct-&gt;setShortcut(tr(&quot;Ctrl+Q&quot;));
 
232
        connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
 
233
 
 
234
        zoomInAct = new QAction(tr(&quot;Zoom &amp;In (25%)&quot;), this);
 
235
        zoomInAct-&gt;setShortcut(tr(&quot;Ctrl++&quot;));
 
236
        zoomInAct-&gt;setEnabled(false);
 
237
        connect(zoomInAct, SIGNAL(triggered()), this, SLOT(zoomIn()));
 
238
 
 
239
        zoomOutAct = new QAction(tr(&quot;Zoom &amp;Out (25%)&quot;), this);
 
240
        zoomOutAct-&gt;setShortcut(tr(&quot;Ctrl+-&quot;));
 
241
        zoomOutAct-&gt;setEnabled(false);
 
242
        connect(zoomOutAct, SIGNAL(triggered()), this, SLOT(zoomOut()));
 
243
 
 
244
        normalSizeAct = new QAction(tr(&quot;&amp;Normal Size&quot;), this);
 
245
        normalSizeAct-&gt;setShortcut(tr(&quot;Ctrl+S&quot;));
 
246
        normalSizeAct-&gt;setEnabled(false);
 
247
        connect(normalSizeAct, SIGNAL(triggered()), this, SLOT(normalSize()));
 
248
 
 
249
        fitToWindowAct = new QAction(tr(&quot;&amp;Fit to Window&quot;), this);
 
250
        fitToWindowAct-&gt;setEnabled(false);
 
251
        fitToWindowAct-&gt;setCheckable(true);
 
252
        fitToWindowAct-&gt;setShortcut(tr(&quot;Ctrl+F&quot;));
 
253
        connect(fitToWindowAct, SIGNAL(triggered()), this, SLOT(fitToWindow()));
 
254
 
 
255
        aboutAct = new QAction(tr(&quot;&amp;About&quot;), this);
 
256
        connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
 
257
 
 
258
        aboutQtAct = new QAction(tr(&quot;About &amp;Qt&quot;), this);
 
259
        connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
 
260
    }</pre>
 
261
<p>In the private <tt>createAction()</tt> function, we create the actions providing the application features.</p>
 
262
<p>We assign a short-cut key to each action and connect them to the appropiate slots. We only enable the <tt>openAct</tt> and <tt>exitAxt</tt> at the time of creation, the others are updated once an image has been loaded into the application. In addition we make the <tt>fitToWindowAct</tt> <a href="qaction.html#checkable-prop">checkable</a>.</p>
 
263
<pre>&nbsp;   void ImageViewer::createMenus()
 
264
    {
 
265
        fileMenu = new QMenu(tr(&quot;&amp;File&quot;), this);
 
266
        fileMenu-&gt;addAction(openAct);
 
267
        fileMenu-&gt;addAction(printAct);
 
268
        fileMenu-&gt;addSeparator();
 
269
        fileMenu-&gt;addAction(exitAct);
 
270
 
 
271
        viewMenu = new QMenu(tr(&quot;&amp;View&quot;), this);
 
272
        viewMenu-&gt;addAction(zoomInAct);
 
273
        viewMenu-&gt;addAction(zoomOutAct);
 
274
        viewMenu-&gt;addAction(normalSizeAct);
 
275
        viewMenu-&gt;addSeparator();
 
276
        viewMenu-&gt;addAction(fitToWindowAct);
 
277
 
 
278
        helpMenu = new QMenu(tr(&quot;&amp;Help&quot;), this);
 
279
        helpMenu-&gt;addAction(aboutAct);
 
280
        helpMenu-&gt;addAction(aboutQtAct);
 
281
 
 
282
        menuBar()-&gt;addMenu(fileMenu);
 
283
        menuBar()-&gt;addMenu(viewMenu);
 
284
        menuBar()-&gt;addMenu(helpMenu);
 
285
    }</pre>
 
286
<p>In the private <tt>createMenu()</tt> function, we add the previously created actions to the <b>File</b>, <b>View</b> and <b>Help</b> menus.</p>
 
287
<p>The <a href="qmenu.html">QMenu</a> class provides a menu widget for use in menu bars, context menus, and other popup menus. The <a href="qmenubar.html">QMenuBar</a> class provides a horizontal menu bar that consists of a list of pull-down menu items. So at the end we put the menus in the <tt>ImageViewer</tt>'s menu bar which we retrieve with the <a href="qmainwindow.html#menuBar">QMainWindow::menuBar</a>() function.</p>
 
288
<pre>&nbsp;   void ImageViewer::updateActions()
 
289
    {
 
290
        zoomInAct-&gt;setEnabled(!fitToWindowAct-&gt;isChecked());
 
291
        zoomOutAct-&gt;setEnabled(!fitToWindowAct-&gt;isChecked());
 
292
        normalSizeAct-&gt;setEnabled(!fitToWindowAct-&gt;isChecked());
 
293
    }</pre>
 
294
<p>The private <tt>updateActions()</tt> function enables or disables the <b>Zoom In</b>, <b>Zoom Out</b> and <b>Normal Size</b> menu entries depending on whether the <b>Fit to Window</b> option is turned on or off.</p>
 
295
<pre>&nbsp;   void ImageViewer::scaleImage(double factor)
 
296
    {
 
297
        Q_ASSERT(imageLabel-&gt;pixmap());
 
298
        scaleFactor *= factor;
 
299
        imageLabel-&gt;resize(scaleFactor * imageLabel-&gt;pixmap()-&gt;size());
 
300
 
 
301
        adjustScrollBar(scrollArea-&gt;horizontalScrollBar(), factor);
 
302
        adjustScrollBar(scrollArea-&gt;verticalScrollBar(), factor);
 
303
 
 
304
        zoomInAct-&gt;setEnabled(scaleFactor &lt; 3.0);
 
305
        zoomOutAct-&gt;setEnabled(scaleFactor &gt; 0.333);
 
306
    }</pre>
 
307
<p>In <tt>scaleImage()</tt>, we use the <tt>factor</tt> parameter to calculate the new scaling factor for the displayed image, and resize <tt>imageLabel</tt>. Since we set the <a href="qlabel.html#scaledContents-prop">scaledContents</a> property to <tt>true</tt> in the constructor, the call to <a href="qwidget.html#size-prop">QWidget::resize</a>() will scale the image displayed in the label. We also adjust the scroll bars to preserve the focal point of the image.</p>
 
308
<p>At the end, if the scale factor is less than 33.3% or greater than 300%, we disable the respective menu entry to prevent the image pixmap from becoming too large, consuming too much resources in the window system.</p>
 
309
<pre>&nbsp;   void ImageViewer::adjustScrollBar(QScrollBar *scrollBar, double factor)
 
310
    {
 
311
        scrollBar-&gt;setValue(int(factor * scrollBar-&gt;value()
 
312
                                + ((factor - 1) * scrollBar-&gt;pageStep()/2)));
 
313
    }</pre>
 
314
<p>Whenever we zoom in or out, we need to adjust the scroll bars in consequence. It would have been tempting to simply call</p>
 
315
<pre>&nbsp;   scrollBar-&gt;setValue(int(factor * scrollBar-&gt;value()));</pre>
 
316
<p>but this would make the top-left corner the focal point, not the center. Therefore we need to take into account the scroll bar handle's size (the <a href="qabstractslider.html#pageStep-prop">page step</a>).</p>
 
317
<p /><address><hr /><div align="center">
 
318
<table width="100%" cellspacing="0" border="0"><tr class="address">
 
319
<td width="30%">Copyright &copy; 2005 <a href="trolltech.html">Trolltech</a></td>
 
320
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
 
321
<td width="30%" align="right"><div align="right">Qt 4.0.0</div></td>
 
322
</tr></table></div></address></body>
 
323
</html>