Sophie

Sophie

distrib > Mageia > 6 > armv5tl > media > core-updates > by-pkgid > 768f7d9f703884aa2562bf0a651086df > files > 4508

qtbase5-doc-5.9.4-1.1.mga6.noarch.rpm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- imageviewer.qdoc -->
  <title>Image Viewer Example | Qt Widgets 5.9</title>
  <link rel="stylesheet" type="text/css" href="style/offline-simple.css" />
  <script type="text/javascript">
    document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");
    // loading style sheet breaks anchors that were jumped to before
    // so force jumping to anchor again
    setTimeout(function() {
        var anchor = location.hash;
        // need to jump to different anchor first (e.g. none)
        location.hash = "#";
        setTimeout(function() {
            location.hash = anchor;
        }, 0);
    }, 0);
  </script>
</head>
<body>
<div class="header" id="qtdocheader">
  <div class="main">
    <div class="main-rounded">
      <div class="navigationbar">
        <table><tr>
<td >Qt 5.9</td><td ><a href="qtwidgets-index.html">Qt Widgets</a></td><td ><a href="examples-widgets.html">Qt Widgets Examples</a></td><td >Image Viewer Example</td></tr></table><table class="buildversion"><tr>
<td id="buildversion" width="100%" align="right">Qt 5.9.4 Reference Documentation</td>
        </tr></table>
      </div>
    </div>
<div class="content">
<div class="line">
<div class="content mainContent">
<div class="sidebar">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#imageviewer-class-definition">ImageViewer Class Definition</a></li>
<li class="level1"><a href="#imageviewer-class-implementation">ImageViewer Class Implementation</a></li>
</ul>
</div>
<div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">Image Viewer Example</h1>
<span class="subtitle"></span>
<!-- $$$widgets/imageviewer-description -->
<div class="descr"> <a name="details"></a>
<p><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>
<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="../qtgui/qpainter.html">QPainter</a> to print an image.</p>
<div class="border"><p class="centerAlign"><img src="images/imageviewer-example.png" alt="" /></p></div><p class="figCaption">Screenshot of the Image Viewer example</p>
<p>With the Image Viewer application, the users can view an image of their choice. The <b>File</b> menu gives the user the possibility to:</p>
<ul>
<li><b>Open..&#x2e;</b> - Open an image file</li>
<li><b>Print..&#x2e;</b> - Print an image</li>
<li><b>Exit</b> - Exit the application</li>
</ul>
<p>Once an image is loaded, the <b>View</b> menu allows the users to:</p>
<ul>
<li><b>Zoom In</b> - Scale the image up by 25%</li>
<li><b>Zoom Out</b> - Scale the image down by 25%</li>
<li><b>Normal Size</b> - Show the image at its original size</li>
<li><b>Fit to Window</b> - Stretch the image to occupy the entire window</li>
</ul>
<p>In addition the <b>Help</b> menu provides the users with information about the Image Viewer example in particular, and about Qt in general.</p>
<a name="imageviewer-class-definition"></a>
<h2 id="imageviewer-class-definition">ImageViewer Class Definition</h2>
<pre class="cpp">

  <span class="keyword">class</span> ImageViewer : <span class="keyword">public</span> <span class="type"><a href="qmainwindow.html">QMainWindow</a></span>
  {
      Q_OBJECT

  <span class="keyword">public</span>:
      ImageViewer();
      bool loadFile(<span class="keyword">const</span> <span class="type"><a href="../qtcore/qstring.html">QString</a></span> <span class="operator">&amp;</span>);

  <span class="keyword">private</span> <span class="keyword">slots</span>:
      <span class="type">void</span> open();
      <span class="type">void</span> saveAs();
      <span class="type">void</span> print();
      <span class="type">void</span> copy();
      <span class="type">void</span> paste();
      <span class="type">void</span> zoomIn();
      <span class="type">void</span> zoomOut();
      <span class="type">void</span> normalSize();
      <span class="type">void</span> fitToWindow();
      <span class="type">void</span> about();

  <span class="keyword">private</span>:
      <span class="type">void</span> createActions();
      <span class="type">void</span> createMenus();
      <span class="type">void</span> updateActions();
      bool saveFile(<span class="keyword">const</span> <span class="type"><a href="../qtcore/qstring.html">QString</a></span> <span class="operator">&amp;</span>fileName);
      <span class="type">void</span> setImage(<span class="keyword">const</span> <span class="type"><a href="../qtgui/qimage.html">QImage</a></span> <span class="operator">&amp;</span>newImage);
      <span class="type">void</span> scaleImage(<span class="type">double</span> factor);
      <span class="type">void</span> adjustScrollBar(<span class="type"><a href="qscrollbar.html">QScrollBar</a></span> <span class="operator">*</span>scrollBar<span class="operator">,</span> <span class="type">double</span> factor);

      <span class="type"><a href="../qtgui/qimage.html">QImage</a></span> image;
      <span class="type"><a href="qlabel.html">QLabel</a></span> <span class="operator">*</span>imageLabel;
      <span class="type"><a href="qscrollarea.html">QScrollArea</a></span> <span class="operator">*</span>scrollArea;
      <span class="type">double</span> scaleFactor;

  <span class="preprocessor">#ifndef QT_NO_PRINTER</span>
      <span class="type">QPrinter</span> printer;
  <span class="preprocessor">#endif</span>

      <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>saveAsAct;
      <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>printAct;
      <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>copyAct;
      <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>zoomInAct;
      <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>zoomOutAct;
      <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>normalSizeAct;
      <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>fitToWindowAct;
  };

</pre>
<p>The <code>ImageViewer</code> 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>
<p>We use <code>createActions()</code> and <code>createMenus()</code> when constructing the <code>ImageViewer</code> widget. We use the <code>updateActions()</code> 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 <code>scaleImage()</code> to perform the zooming. In turn, <code>scaleImage()</code> uses <code>adjustScrollBar()</code> to preserve the focal point after scaling an image.</p>
<a name="imageviewer-class-implementation"></a>
<h2 id="imageviewer-class-implementation">ImageViewer Class Implementation</h2>
<pre class="cpp">

  ImageViewer<span class="operator">::</span>ImageViewer()
     : imageLabel(<span class="keyword">new</span> <span class="type"><a href="qlabel.html">QLabel</a></span>)
     <span class="operator">,</span> scrollArea(<span class="keyword">new</span> <span class="type"><a href="qscrollarea.html">QScrollArea</a></span>)
     <span class="operator">,</span> scaleFactor(<span class="number">1</span>)
  {
      imageLabel<span class="operator">-</span><span class="operator">&gt;</span>setBackgroundRole(<span class="type"><a href="../qtgui/qpalette.html">QPalette</a></span><span class="operator">::</span>Base);
      imageLabel<span class="operator">-</span><span class="operator">&gt;</span>setSizePolicy(<span class="type"><a href="qsizepolicy.html">QSizePolicy</a></span><span class="operator">::</span>Ignored<span class="operator">,</span> <span class="type"><a href="qsizepolicy.html">QSizePolicy</a></span><span class="operator">::</span>Ignored);
      imageLabel<span class="operator">-</span><span class="operator">&gt;</span>setScaledContents(<span class="keyword">true</span>);

      scrollArea<span class="operator">-</span><span class="operator">&gt;</span>setBackgroundRole(<span class="type"><a href="../qtgui/qpalette.html">QPalette</a></span><span class="operator">::</span>Dark);
      scrollArea<span class="operator">-</span><span class="operator">&gt;</span>setWidget(imageLabel);
      scrollArea<span class="operator">-</span><span class="operator">&gt;</span>setVisible(<span class="keyword">false</span>);
      setCentralWidget(scrollArea);

      createActions();

      resize(<span class="type"><a href="../qtgui/qguiapplication.html">QGuiApplication</a></span><span class="operator">::</span>primaryScreen()<span class="operator">-</span><span class="operator">&gt;</span>availableSize() <span class="operator">*</span> <span class="number">3</span> <span class="operator">/</span> <span class="number">5</span>);
  }

</pre>
<p>In the constructor we first create the label and the scroll area.</p>
<p>We set <code>imageLabel</code>'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>
<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 <code>imageLabel</code>'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>
<p>We make <code>imageLabel</code> the scroll area's child widget, and we make <code>scrollArea</code> the central widget of the <a href="qmainwindow.html">QMainWindow</a>. At the end we create the associated actions and menus, and customize the <code>ImageViewer</code>'s appearance.</p>
<pre class="cpp">

  <span class="keyword">static</span> <span class="type">void</span> initializeImageFileDialog(<span class="type"><a href="qfiledialog.html">QFileDialog</a></span> <span class="operator">&amp;</span>dialog<span class="operator">,</span> <span class="type"><a href="qfiledialog.html">QFileDialog</a></span><span class="operator">::</span>AcceptMode acceptMode)
  {
      <span class="keyword">static</span> bool firstDialog <span class="operator">=</span> <span class="keyword">true</span>;

      <span class="keyword">if</span> (firstDialog) {
          firstDialog <span class="operator">=</span> <span class="keyword">false</span>;
          <span class="keyword">const</span> <span class="type"><a href="../qtcore/qstringlist.html">QStringList</a></span> picturesLocations <span class="operator">=</span> <span class="type"><a href="../qtcore/qstandardpaths.html">QStandardPaths</a></span><span class="operator">::</span>standardLocations(<span class="type"><a href="../qtcore/qstandardpaths.html">QStandardPaths</a></span><span class="operator">::</span>PicturesLocation);
          dialog<span class="operator">.</span>setDirectory(picturesLocations<span class="operator">.</span>isEmpty() <span class="operator">?</span> <span class="type"><a href="../qtcore/qdir.html">QDir</a></span><span class="operator">::</span>currentPath() : picturesLocations<span class="operator">.</span>last());
      }

      <span class="type"><a href="../qtcore/qstringlist.html">QStringList</a></span> mimeTypeFilters;
      <span class="keyword">const</span> <span class="type"><a href="../qtcore/qbytearraylist.html">QByteArrayList</a></span> supportedMimeTypes <span class="operator">=</span> acceptMode <span class="operator">=</span><span class="operator">=</span> <span class="type"><a href="qfiledialog.html">QFileDialog</a></span><span class="operator">::</span>AcceptOpen
          <span class="operator">?</span> <span class="type"><a href="../qtgui/qimagereader.html">QImageReader</a></span><span class="operator">::</span>supportedMimeTypes() : <span class="type"><a href="../qtgui/qimagewriter.html">QImageWriter</a></span><span class="operator">::</span>supportedMimeTypes();
      foreach (<span class="keyword">const</span> <span class="type"><a href="../qtcore/qbytearray.html">QByteArray</a></span> <span class="operator">&amp;</span>mimeTypeName<span class="operator">,</span> supportedMimeTypes)
          mimeTypeFilters<span class="operator">.</span>append(mimeTypeName);
      mimeTypeFilters<span class="operator">.</span>sort();
      dialog<span class="operator">.</span>setMimeTypeFilters(mimeTypeFilters);
      dialog<span class="operator">.</span>selectMimeTypeFilter(<span class="string">&quot;image/jpeg&quot;</span>);
      <span class="keyword">if</span> (acceptMode <span class="operator">=</span><span class="operator">=</span> <span class="type"><a href="qfiledialog.html">QFileDialog</a></span><span class="operator">::</span>AcceptSave)
          dialog<span class="operator">.</span>setDefaultSuffix(<span class="string">&quot;jpg&quot;</span>);
  }

  <span class="type">void</span> ImageViewer<span class="operator">::</span>open()
  {
      <span class="type"><a href="qfiledialog.html">QFileDialog</a></span> dialog(<span class="keyword">this</span><span class="operator">,</span> tr(<span class="string">&quot;Open File&quot;</span>));
      initializeImageFileDialog(dialog<span class="operator">,</span> <span class="type"><a href="qfiledialog.html">QFileDialog</a></span><span class="operator">::</span>AcceptOpen);

      <span class="keyword">while</span> (dialog<span class="operator">.</span>exec() <span class="operator">=</span><span class="operator">=</span> <span class="type"><a href="qdialog.html">QDialog</a></span><span class="operator">::</span>Accepted <span class="operator">&amp;</span><span class="operator">&amp;</span> <span class="operator">!</span>loadFile(dialog<span class="operator">.</span>selectedFiles()<span class="operator">.</span>first())) {}
  }

</pre>
<p>In the <code>open()</code> slot, we show a file dialog to the user. We compile a list of mime types for use as a filter by querying <a href="../qtgui/qimagereader.html">QImageReader</a> for the available mime type names.</p>
<p>We show the file dialog until a valid file name is entered or the user cancels.</p>
<p>The function <code>loadFile()</code> is used to load the image.</p>
<pre class="cpp">

  bool ImageViewer<span class="operator">::</span>loadFile(<span class="keyword">const</span> <span class="type"><a href="../qtcore/qstring.html">QString</a></span> <span class="operator">&amp;</span>fileName)
  {
      <span class="type"><a href="../qtgui/qimagereader.html">QImageReader</a></span> reader(fileName);
      reader<span class="operator">.</span>setAutoTransform(<span class="keyword">true</span>);
      <span class="keyword">const</span> <span class="type"><a href="../qtgui/qimage.html">QImage</a></span> newImage <span class="operator">=</span> reader<span class="operator">.</span>read();
      <span class="keyword">if</span> (newImage<span class="operator">.</span>isNull()) {
          <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>information(<span class="keyword">this</span><span class="operator">,</span> <span class="type"><a href="../qtgui/qguiapplication.html">QGuiApplication</a></span><span class="operator">::</span>applicationDisplayName()<span class="operator">,</span>
                                   tr(<span class="string">&quot;Cannot load %1: %2&quot;</span>)
                                   <span class="operator">.</span>arg(<span class="type"><a href="../qtcore/qdir.html">QDir</a></span><span class="operator">::</span>toNativeSeparators(fileName)<span class="operator">,</span> reader<span class="operator">.</span>errorString()));
          <span class="keyword">return</span> <span class="keyword">false</span>;
      }

</pre>
<p>In the <code>loadFile()</code> function, we instantiate a <a href="../qtgui/qimagereader.html">QImageReader</a> and enable automatic transformations by calling <a href="../qtgui/qimagereader.html#setAutoTransform">QImageReader::setAutoTransform</a>(). For files in JPEG format, this ensures that portrait mode images of digital cameras are shown correctly by applying the appropriate orientation read from the EXIF meta data stored in the image file.</p>
<p>We then load the image using <a href="../qtgui/qimagereader.html#read">QImageReader::read</a>(). If this returns a null image, indicating that the file is not an image file, we use a <a href="qmessagebox.html">QMessageBox</a> to alert the user.</p>
<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>
<pre class="cpp">

      scaleFactor <span class="operator">=</span> <span class="number">1.0</span>;

      scrollArea<span class="operator">-</span><span class="operator">&gt;</span>setVisible(<span class="keyword">true</span>);
      printAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">true</span>);
      fitToWindowAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">true</span>);
      updateActions();

      <span class="keyword">if</span> (<span class="operator">!</span>fitToWindowAct<span class="operator">-</span><span class="operator">&gt;</span>isChecked())
          imageLabel<span class="operator">-</span><span class="operator">&gt;</span>adjustSize();
  }

</pre>
<p>If the format is supported, we display the image in <code>imageLabel</code> 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>
<p>If the <b>Fit to Window</b> option is turned off, the <a href="qscrollarea.html#widgetResizable-prop">QScrollArea::widgetResizable</a> property is <code>false</code> and 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>
<pre class="cpp">

  imageLabel<span class="operator">-</span><span class="operator">&gt;</span>resize(imageLabel<span class="operator">-</span><span class="operator">&gt;</span>pixmap()<span class="operator">-</span><span class="operator">&gt;</span>size());

</pre>
<p>In the <code>print()</code> slot, we first make sure that an image has been loaded into the application:</p>
<pre class="cpp">

  <span class="type">void</span> ImageViewer<span class="operator">::</span>print()
  {
      Q_ASSERT(imageLabel<span class="operator">-</span><span class="operator">&gt;</span>pixmap());
  <span class="preprocessor">#if QT_CONFIG(printdialog)</span>

</pre>
<p>If the application is built in debug mode, the <code>Q_ASSERT()</code> macro will expand to</p>
<pre class="cpp">

  <span class="keyword">if</span> (<span class="operator">!</span>imageLabel<span class="operator">-</span><span class="operator">&gt;</span>pixmap())
      <a href="../qtcore/qtglobal.html#qFatal">qFatal</a>(<span class="string">&quot;ASSERT: &quot;</span>imageLabel<span class="operator">-</span><span class="operator">&gt;</span>pixmap()<span class="string">&quot; in file ...&quot;</span>);

</pre>
<p>In release mode, the macro simply disappear. The mode can be set in the application's <code>.pro</code> file. One way to do so is to add an option to <b>qmake</b> when building the application:</p>
<pre class="cpp">

  qmake <span class="string">&quot;CONFIG += debug&quot;</span> foo<span class="operator">.</span>pro

</pre>
<p>or</p>
<pre class="cpp">

  qmake <span class="string">&quot;CONFIG += release&quot;</span> foo<span class="operator">.</span>pro

</pre>
<p>Another approach is to add this line directly to the <code>.pro</code> file.</p>
<pre class="cpp">

      <span class="type">QPrintDialog</span> dialog(<span class="operator">&amp;</span>printer<span class="operator">,</span> <span class="keyword">this</span>);
      <span class="keyword">if</span> (dialog<span class="operator">.</span>exec()) {
          <span class="type"><a href="../qtgui/qpainter.html">QPainter</a></span> painter(<span class="operator">&amp;</span>printer);
          <span class="type"><a href="../qtcore/qrect.html">QRect</a></span> rect <span class="operator">=</span> painter<span class="operator">.</span>viewport();
          <span class="type"><a href="../qtcore/qsize.html">QSize</a></span> size <span class="operator">=</span> imageLabel<span class="operator">-</span><span class="operator">&gt;</span>pixmap()<span class="operator">-</span><span class="operator">&gt;</span>size();
          size<span class="operator">.</span>scale(rect<span class="operator">.</span>size()<span class="operator">,</span> <span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>KeepAspectRatio);
          painter<span class="operator">.</span>setViewport(rect<span class="operator">.</span>x()<span class="operator">,</span> rect<span class="operator">.</span>y()<span class="operator">,</span> size<span class="operator">.</span>width()<span class="operator">,</span> size<span class="operator">.</span>height());
          painter<span class="operator">.</span>setWindow(imageLabel<span class="operator">-</span><span class="operator">&gt;</span>pixmap()<span class="operator">-</span><span class="operator">&gt;</span>rect());
          painter<span class="operator">.</span>drawPixmap(<span class="number">0</span><span class="operator">,</span> <span class="number">0</span><span class="operator">,</span> <span class="operator">*</span>imageLabel<span class="operator">-</span><span class="operator">&gt;</span>pixmap());
      }
  <span class="preprocessor">#endif</span>
  }

</pre>
<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 QPrinter 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="../qtcore/qt.html#AspectRatioMode-enum">aspect ratio</a>.</p>
<p>In the end we draw the pixmap at position (0, 0).</p>
<pre class="cpp">

  <span class="type">void</span> ImageViewer<span class="operator">::</span>zoomIn()
  {
      scaleImage(<span class="number">1.25</span>);
  }

  <span class="type">void</span> ImageViewer<span class="operator">::</span>zoomOut()
  {
      scaleImage(<span class="number">0.8</span>);
  }

</pre>
<p>We implement the zooming slots using the private <code>scaleImage()</code> 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>
<p>The screenshots below show an image in its normal size, and the same image after zooming in:</p>
<div class="table"><table class="generic">
 <tr valign="top" class="odd"><td ><img src="images/imageviewer-original_size.png" alt="" /></td><td ><img src="images/imageviewer-zoom_in_1.png" alt="" /></td><td ><img src="images/imageviewer-zoom_in_2.png" alt="" /></td></tr>
</table></div>
<pre class="cpp">

  <span class="type">void</span> ImageViewer<span class="operator">::</span>normalSize()
  {
      imageLabel<span class="operator">-</span><span class="operator">&gt;</span>adjustSize();
      scaleFactor <span class="operator">=</span> <span class="number">1.0</span>;
  }

</pre>
<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 <code>adjustSize()</code> and reset the scale factor to 1.0&#x2e;</p>
<pre class="cpp">

  <span class="type">void</span> ImageViewer<span class="operator">::</span>fitToWindow()
  {
      bool fitToWindow <span class="operator">=</span> fitToWindowAct<span class="operator">-</span><span class="operator">&gt;</span>isChecked();
      scrollArea<span class="operator">-</span><span class="operator">&gt;</span>setWidgetResizable(fitToWindow);
      <span class="keyword">if</span> (<span class="operator">!</span>fitToWindow)
          normalSize();
      updateActions();
  }

</pre>
<p>The <code>fitToWindow()</code> 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 <code>updateActions()</code> function.</p>
<p>If the <a href="qscrollarea.html#widgetResizable-prop">QScrollArea::widgetResizable</a> property is set to <code>false</code> (the default), the scroll area honors the size of its child widget. If this property is set to <code>true</code>, 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 <code>imageLabel</code>'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>
<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>
<div class="table"><table class="generic">
 <tr valign="top" class="odd"><td ><img src="images/imageviewer-original_size.png" alt="" /></td><td ><img src="images/imageviewer-fit_to_window_1.png" alt="" /></td><td ><img src="images/imageviewer-fit_to_window_2.png" alt="" /></td></tr>
</table></div>
<p>If the slot is called to turn off the option, the {<a href="qscrollarea.html#widgetResizable-prop">QScrollArea::setWidgetResizable</a>} property is set to <code>false</code>. 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>
<pre class="cpp">

  <span class="type">void</span> ImageViewer<span class="operator">::</span>about()
  {
      <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>about(<span class="keyword">this</span><span class="operator">,</span> tr(<span class="string">&quot;About Image Viewer&quot;</span>)<span class="operator">,</span>
              tr(<span class="string">&quot;&lt;p&gt;The &lt;b&gt;Image Viewer&lt;/b&gt; example shows how to combine QLabel &quot;</span>
                 <span class="string">&quot;and QScrollArea to display an image. QLabel is typically used &quot;</span>
                 <span class="string">&quot;for displaying a text, but it can also display an image. &quot;</span>
                 <span class="string">&quot;QScrollArea provides a scrolling view around another widget. &quot;</span>
                 <span class="string">&quot;If the child widget exceeds the size of the frame, QScrollArea &quot;</span>
                 <span class="string">&quot;automatically provides scroll bars. &lt;/p&gt;&lt;p&gt;The example &quot;</span>
                 <span class="string">&quot;demonstrates how QLabel's ability to scale its contents &quot;</span>
                 <span class="string">&quot;(QLabel::scaledContents), and QScrollArea's ability to &quot;</span>
                 <span class="string">&quot;automatically resize its contents &quot;</span>
                 <span class="string">&quot;(QScrollArea::widgetResizable), can be used to implement &quot;</span>
                 <span class="string">&quot;zooming and scaling features. &lt;/p&gt;&lt;p&gt;In addition the example &quot;</span>
                 <span class="string">&quot;shows how to use QPainter to print an image.&lt;/p&gt;&quot;</span>));
  }

</pre>
<p>We implement the <code>about()</code> slot to create a message box describing what the example is designed to show.</p>
<pre class="cpp">

  <span class="type">void</span> ImageViewer<span class="operator">::</span>createActions()
  {
      <span class="type"><a href="qmenu.html">QMenu</a></span> <span class="operator">*</span>fileMenu <span class="operator">=</span> menuBar()<span class="operator">-</span><span class="operator">&gt;</span>addMenu(tr(<span class="string">&quot;&amp;File&quot;</span>));

      <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>openAct <span class="operator">=</span> fileMenu<span class="operator">-</span><span class="operator">&gt;</span>addAction(tr(<span class="string">&quot;&amp;Open...&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> <span class="operator">&amp;</span>ImageViewer<span class="operator">::</span>open);
      openAct<span class="operator">-</span><span class="operator">&gt;</span>setShortcut(<span class="type"><a href="../qtgui/qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>Open);

      saveAsAct <span class="operator">=</span> fileMenu<span class="operator">-</span><span class="operator">&gt;</span>addAction(tr(<span class="string">&quot;&amp;Save As...&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> <span class="operator">&amp;</span>ImageViewer<span class="operator">::</span>saveAs);
      saveAsAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">false</span>);

      printAct <span class="operator">=</span> fileMenu<span class="operator">-</span><span class="operator">&gt;</span>addAction(tr(<span class="string">&quot;&amp;Print...&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> <span class="operator">&amp;</span>ImageViewer<span class="operator">::</span>print);
      printAct<span class="operator">-</span><span class="operator">&gt;</span>setShortcut(<span class="type"><a href="../qtgui/qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>Print);
      printAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">false</span>);

      fileMenu<span class="operator">-</span><span class="operator">&gt;</span>addSeparator();

      <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>exitAct <span class="operator">=</span> fileMenu<span class="operator">-</span><span class="operator">&gt;</span>addAction(tr(<span class="string">&quot;E&amp;xit&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> <span class="operator">&amp;</span><span class="type"><a href="qwidget.html">QWidget</a></span><span class="operator">::</span>close);
      exitAct<span class="operator">-</span><span class="operator">&gt;</span>setShortcut(tr(<span class="string">&quot;Ctrl+Q&quot;</span>));

      <span class="type"><a href="qmenu.html">QMenu</a></span> <span class="operator">*</span>editMenu <span class="operator">=</span> menuBar()<span class="operator">-</span><span class="operator">&gt;</span>addMenu(tr(<span class="string">&quot;&amp;Edit&quot;</span>));

      copyAct <span class="operator">=</span> editMenu<span class="operator">-</span><span class="operator">&gt;</span>addAction(tr(<span class="string">&quot;&amp;Copy&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> <span class="operator">&amp;</span>ImageViewer<span class="operator">::</span>copy);
      copyAct<span class="operator">-</span><span class="operator">&gt;</span>setShortcut(<span class="type"><a href="../qtgui/qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>Copy);
      copyAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">false</span>);

      <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>pasteAct <span class="operator">=</span> editMenu<span class="operator">-</span><span class="operator">&gt;</span>addAction(tr(<span class="string">&quot;&amp;Paste&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> <span class="operator">&amp;</span>ImageViewer<span class="operator">::</span>paste);
      pasteAct<span class="operator">-</span><span class="operator">&gt;</span>setShortcut(<span class="type"><a href="../qtgui/qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>Paste);

      <span class="type"><a href="qmenu.html">QMenu</a></span> <span class="operator">*</span>viewMenu <span class="operator">=</span> menuBar()<span class="operator">-</span><span class="operator">&gt;</span>addMenu(tr(<span class="string">&quot;&amp;View&quot;</span>));

      zoomInAct <span class="operator">=</span> viewMenu<span class="operator">-</span><span class="operator">&gt;</span>addAction(tr(<span class="string">&quot;Zoom &amp;In (25%)&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> <span class="operator">&amp;</span>ImageViewer<span class="operator">::</span>zoomIn);
      zoomInAct<span class="operator">-</span><span class="operator">&gt;</span>setShortcut(<span class="type"><a href="../qtgui/qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>ZoomIn);
      zoomInAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">false</span>);

      zoomOutAct <span class="operator">=</span> viewMenu<span class="operator">-</span><span class="operator">&gt;</span>addAction(tr(<span class="string">&quot;Zoom &amp;Out (25%)&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> <span class="operator">&amp;</span>ImageViewer<span class="operator">::</span>zoomOut);
      zoomOutAct<span class="operator">-</span><span class="operator">&gt;</span>setShortcut(<span class="type"><a href="../qtgui/qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>ZoomOut);
      zoomOutAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">false</span>);

      normalSizeAct <span class="operator">=</span> viewMenu<span class="operator">-</span><span class="operator">&gt;</span>addAction(tr(<span class="string">&quot;&amp;Normal Size&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> <span class="operator">&amp;</span>ImageViewer<span class="operator">::</span>normalSize);
      normalSizeAct<span class="operator">-</span><span class="operator">&gt;</span>setShortcut(tr(<span class="string">&quot;Ctrl+S&quot;</span>));
      normalSizeAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">false</span>);

      viewMenu<span class="operator">-</span><span class="operator">&gt;</span>addSeparator();

      fitToWindowAct <span class="operator">=</span> viewMenu<span class="operator">-</span><span class="operator">&gt;</span>addAction(tr(<span class="string">&quot;&amp;Fit to Window&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> <span class="operator">&amp;</span>ImageViewer<span class="operator">::</span>fitToWindow);
      fitToWindowAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="keyword">false</span>);
      fitToWindowAct<span class="operator">-</span><span class="operator">&gt;</span>setCheckable(<span class="keyword">true</span>);
      fitToWindowAct<span class="operator">-</span><span class="operator">&gt;</span>setShortcut(tr(<span class="string">&quot;Ctrl+F&quot;</span>));

      <span class="type"><a href="qmenu.html">QMenu</a></span> <span class="operator">*</span>helpMenu <span class="operator">=</span> menuBar()<span class="operator">-</span><span class="operator">&gt;</span>addMenu(tr(<span class="string">&quot;&amp;Help&quot;</span>));

      helpMenu<span class="operator">-</span><span class="operator">&gt;</span>addAction(tr(<span class="string">&quot;&amp;About&quot;</span>)<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> <span class="operator">&amp;</span>ImageViewer<span class="operator">::</span>about);
      helpMenu<span class="operator">-</span><span class="operator">&gt;</span>addAction(tr(<span class="string">&quot;About &amp;Qt&quot;</span>)<span class="operator">,</span> <span class="operator">&amp;</span><span class="type"><a href="qapplication.html">QApplication</a></span><span class="operator">::</span>aboutQt);
  }

</pre>
<p>In the private <code>createAction()</code> function, we create the actions providing the application features and populate a menu with them.</p>
<p>We assign a short-cut key to each action and connect them to the appropriate slots. We only enable the <code>openAct</code> and <code>exitAct</code> at the time of creation, the others are updated once an image has been loaded into the application. In addition we make the <code>fitToWindowAct</code> <a href="qaction.html#checkable-prop">checkable</a>.</p>
<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 we put the menus in the <code>ImageViewer</code>'s menu bar which we retrieve with the <a href="qmainwindow.html#menuBar">QMainWindow::menuBar</a>() function.</p>
<pre class="cpp">

  <span class="type">void</span> ImageViewer<span class="operator">::</span>updateActions()
  {
      saveAsAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="operator">!</span>image<span class="operator">.</span>isNull());
      copyAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="operator">!</span>image<span class="operator">.</span>isNull());
      zoomInAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="operator">!</span>fitToWindowAct<span class="operator">-</span><span class="operator">&gt;</span>isChecked());
      zoomOutAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="operator">!</span>fitToWindowAct<span class="operator">-</span><span class="operator">&gt;</span>isChecked());
      normalSizeAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(<span class="operator">!</span>fitToWindowAct<span class="operator">-</span><span class="operator">&gt;</span>isChecked());
  }

</pre>
<p>The private <code>updateActions()</code> 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>
<pre class="cpp">

  <span class="type">void</span> ImageViewer<span class="operator">::</span>scaleImage(<span class="type">double</span> factor)
  {
      Q_ASSERT(imageLabel<span class="operator">-</span><span class="operator">&gt;</span>pixmap());
      scaleFactor <span class="operator">*</span><span class="operator">=</span> factor;
      imageLabel<span class="operator">-</span><span class="operator">&gt;</span>resize(scaleFactor <span class="operator">*</span> imageLabel<span class="operator">-</span><span class="operator">&gt;</span>pixmap()<span class="operator">-</span><span class="operator">&gt;</span>size());

      adjustScrollBar(scrollArea<span class="operator">-</span><span class="operator">&gt;</span>horizontalScrollBar()<span class="operator">,</span> factor);
      adjustScrollBar(scrollArea<span class="operator">-</span><span class="operator">&gt;</span>verticalScrollBar()<span class="operator">,</span> factor);

      zoomInAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(scaleFactor <span class="operator">&lt;</span> <span class="number">3.0</span>);
      zoomOutAct<span class="operator">-</span><span class="operator">&gt;</span>setEnabled(scaleFactor <span class="operator">&gt;</span> <span class="number">0.333</span>);
  }

</pre>
<p>In <code>scaleImage()</code>, we use the <code>factor</code> parameter to calculate the new scaling factor for the displayed image, and resize <code>imageLabel</code>. Since we set the <a href="qlabel.html#scaledContents-prop">scaledContents</a> property to <code>true</code> 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>
<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>
<pre class="cpp">

  <span class="type">void</span> ImageViewer<span class="operator">::</span>adjustScrollBar(<span class="type"><a href="qscrollbar.html">QScrollBar</a></span> <span class="operator">*</span>scrollBar<span class="operator">,</span> <span class="type">double</span> factor)
  {
      scrollBar<span class="operator">-</span><span class="operator">&gt;</span>setValue(<span class="type">int</span>(factor <span class="operator">*</span> scrollBar<span class="operator">-</span><span class="operator">&gt;</span>value()
                              <span class="operator">+</span> ((factor <span class="operator">-</span> <span class="number">1</span>) <span class="operator">*</span> scrollBar<span class="operator">-</span><span class="operator">&gt;</span>pageStep()<span class="operator">/</span><span class="number">2</span>)));
  }

</pre>
<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>
<pre class="cpp">

  scrollBar<span class="operator">-</span><span class="operator">&gt;</span>setValue(<span class="type">int</span>(factor <span class="operator">*</span> scrollBar<span class="operator">-</span><span class="operator">&gt;</span>value()));

</pre>
<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>
<p>Files:</p>
<ul>
<li><a href="qtwidgets-widgets-imageviewer-imageviewer-cpp.html">widgets/imageviewer/imageviewer.cpp</a></li>
<li><a href="qtwidgets-widgets-imageviewer-imageviewer-h.html">widgets/imageviewer/imageviewer.h</a></li>
<li><a href="qtwidgets-widgets-imageviewer-main-cpp.html">widgets/imageviewer/main.cpp</a></li>
<li><a href="qtwidgets-widgets-imageviewer-imageviewer-pro.html">widgets/imageviewer/imageviewer.pro</a></li>
</ul>
</div>
<!-- @@@widgets/imageviewer -->
        </div>
       </div>
   </div>
   </div>
</div>
<div class="footer">
   <p>
   <acronym title="Copyright">&copy;</acronym> 2017 The Qt Company Ltd.
   Documentation contributions included herein are the copyrights of
   their respective owners.<br>    The documentation provided herein is licensed under the terms of the    <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation    License version 1.3</a> as published by the Free Software Foundation.<br>    Qt and respective logos are trademarks of The Qt Company Ltd.     in Finland and/or other countries worldwide. All other trademarks are property
   of their respective owners. </p>
</div>
</body>
</html>