1
<?xml version="1.0" encoding="iso-8859-1"?>
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 -->
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>
16
<table border="0" cellpadding="0" cellspacing="0" width="100%">
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"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a> · <a href="classes.html"><font color="#004faf">All Classes</font></a> · <a href="mainclasses.html"><font color="#004faf">Main Classes</font></a> · <a href="annotated.html"><font color="#004faf">Annotated</font></a> · <a href="groups.html"><font color="#004faf">Grouped Classes</font></a> · <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>
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>
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>
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>
35
<p>Once an image is loaded, the <b>View</b> menu allows the users to:</p>
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>
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> class ImageViewer : public QMainWindow
65
void scaleImage(double factor);
66
void adjustScrollBar(QScrollBar *scrollBar, double factor);
69
QScrollArea *scrollArea;
79
QAction *normalSizeAct;
80
QAction *fitToWindowAct;
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> ImageViewer::ImageViewer()
94
imageLabel = new QLabel;
95
imageLabel->setBackgroundRole(QPalette::Base);
96
imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
97
imageLabel->setScaledContents(true);
99
scrollArea = new QScrollArea;
100
scrollArea->setBackgroundRole(QPalette::Dark);
101
scrollArea->setWidget(imageLabel);
102
setCentralWidget(scrollArea);
107
setWindowTitle(tr("Image Viewer"));
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> void ImageViewer::open()
116
QString fileName = QFileDialog::getOpenFileName(this,
117
tr("Open File"), QDir::currentPath());
118
if (!fileName.isEmpty()) {
119
QImage image(fileName);
120
if (image.isNull()) {
121
QMessageBox::information(this, tr("Image Viewer"),
122
tr("Cannot load %1.").arg(fileName));
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> imageLabel->setPixmap(QPixmap::fromImage(image));
131
printAct->setEnabled(true);
132
fitToWindowAct->setEnabled(true);
135
if (!fitToWindowAct->isChecked())
136
imageLabel->adjustSize();
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> imageLabel->resize(imageLabel->pixmap()->size());
142
void ImageViewer::print()
144
Q_ASSERT(imageLabel->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> if (!imageLabel->pixmap())
147
qFatal("ASSERT: "imageLabel->pixmap()" in file ...");</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> qmake "CONFIG += debug" foo.pro</pre>
151
<pre> qmake "CONFIG += release" foo.pro</pre>
152
<p>Another approach is to add this line directly to the <tt>.pro</tt> file.</p>
153
<pre> QPrintDialog dialog(&printer, this);
155
QPainter painter(&printer);
156
QRect rect = painter.viewport();
157
QSize size = imageLabel->pixmap()->size();
158
size.scale(rect.size(), Qt::KeepAspectRatio);
159
painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
160
painter.setWindow(imageLabel->pixmap()->rect());
161
painter.drawPixmap(0, 0, *imageLabel->pixmap());
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> void ImageViewer::zoomIn()
171
void ImageViewer::zoomOut()
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>
180
<pre> void ImageViewer::normalSize()
182
imageLabel->adjustSize();
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> void ImageViewer::fitToWindow()
188
bool fitToWindow = fitToWindowAct->isChecked();
189
scrollArea->setWidgetResizable(fitToWindow);
191
imageLabel->adjustSize();
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>
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> void ImageViewer::about()
204
QMessageBox::about(this, tr("About Image Viewer"),
205
tr("<p>The <b>Image Viewer</b> example shows how to combine QLabel "
206
"and QScrollArea to display an image. QLabel is typically used "
207
"for displaying a text, but it can also display an image. "
208
"QScrollArea provides a scrolling view around another widget. "
209
"If the child widget exceeds the size of the frame, QScrollArea "
210
"automatically provides scroll bars. </p><p>The example "
211
"demonstrates how QLabel's ability to scale its contents "
212
"(QLabel::scaledContents), and QScrollArea's ability to "
213
"automatically resize its contents "
214
"(QScrollArea::widgetResizable), can be used to implement "
215
"zooming and scaling features. </p><p>In addition the example "
216
"shows how to use QPainter to print an image.</p>"));
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> void ImageViewer::createActions()
221
openAct = new QAction(tr("&Open..."), this);
222
openAct->setShortcut(tr("Ctrl+O"));
223
connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
225
printAct = new QAction(tr("&Print..."), this);
226
printAct->setShortcut(tr("Ctrl+P"));
227
printAct->setEnabled(false);
228
connect(printAct, SIGNAL(triggered()), this, SLOT(print()));
230
exitAct = new QAction(tr("E&xit"), this);
231
exitAct->setShortcut(tr("Ctrl+Q"));
232
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
234
zoomInAct = new QAction(tr("Zoom &In (25%)"), this);
235
zoomInAct->setShortcut(tr("Ctrl++"));
236
zoomInAct->setEnabled(false);
237
connect(zoomInAct, SIGNAL(triggered()), this, SLOT(zoomIn()));
239
zoomOutAct = new QAction(tr("Zoom &Out (25%)"), this);
240
zoomOutAct->setShortcut(tr("Ctrl+-"));
241
zoomOutAct->setEnabled(false);
242
connect(zoomOutAct, SIGNAL(triggered()), this, SLOT(zoomOut()));
244
normalSizeAct = new QAction(tr("&Normal Size"), this);
245
normalSizeAct->setShortcut(tr("Ctrl+S"));
246
normalSizeAct->setEnabled(false);
247
connect(normalSizeAct, SIGNAL(triggered()), this, SLOT(normalSize()));
249
fitToWindowAct = new QAction(tr("&Fit to Window"), this);
250
fitToWindowAct->setEnabled(false);
251
fitToWindowAct->setCheckable(true);
252
fitToWindowAct->setShortcut(tr("Ctrl+F"));
253
connect(fitToWindowAct, SIGNAL(triggered()), this, SLOT(fitToWindow()));
255
aboutAct = new QAction(tr("&About"), this);
256
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
258
aboutQtAct = new QAction(tr("About &Qt"), this);
259
connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
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> void ImageViewer::createMenus()
265
fileMenu = new QMenu(tr("&File"), this);
266
fileMenu->addAction(openAct);
267
fileMenu->addAction(printAct);
268
fileMenu->addSeparator();
269
fileMenu->addAction(exitAct);
271
viewMenu = new QMenu(tr("&View"), this);
272
viewMenu->addAction(zoomInAct);
273
viewMenu->addAction(zoomOutAct);
274
viewMenu->addAction(normalSizeAct);
275
viewMenu->addSeparator();
276
viewMenu->addAction(fitToWindowAct);
278
helpMenu = new QMenu(tr("&Help"), this);
279
helpMenu->addAction(aboutAct);
280
helpMenu->addAction(aboutQtAct);
282
menuBar()->addMenu(fileMenu);
283
menuBar()->addMenu(viewMenu);
284
menuBar()->addMenu(helpMenu);
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> void ImageViewer::updateActions()
290
zoomInAct->setEnabled(!fitToWindowAct->isChecked());
291
zoomOutAct->setEnabled(!fitToWindowAct->isChecked());
292
normalSizeAct->setEnabled(!fitToWindowAct->isChecked());
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> void ImageViewer::scaleImage(double factor)
297
Q_ASSERT(imageLabel->pixmap());
298
scaleFactor *= factor;
299
imageLabel->resize(scaleFactor * imageLabel->pixmap()->size());
301
adjustScrollBar(scrollArea->horizontalScrollBar(), factor);
302
adjustScrollBar(scrollArea->verticalScrollBar(), factor);
304
zoomInAct->setEnabled(scaleFactor < 3.0);
305
zoomOutAct->setEnabled(scaleFactor > 0.333);
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> void ImageViewer::adjustScrollBar(QScrollBar *scrollBar, double factor)
311
scrollBar->setValue(int(factor * scrollBar->value()
312
+ ((factor - 1) * scrollBar->pageStep()/2)));
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> scrollBar->setValue(int(factor * scrollBar->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 © 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>