Sophie

Sophie

distrib > Mageia > 7 > armv7hl > media > core-updates > by-pkgid > d5e62c01ae8d1e579463c6a871dd44bf > files > 5052

qtbase5-doc-5.12.6-2.mga7.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" />
<!-- codeeditor.qdoc -->
  <title>Code Editor Example | Qt Widgets 5.12.6</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.12</td><td ><a href="qtwidgets-index.html">Qt Widgets</a></td><td ><a href="examples-widgets.html">Qt Widgets Examples</a></td><td >Code Editor Example</td></tr></table><table class="buildversion"><tr>
<td id="buildversion" width="100%" align="right"><a href="qtwidgets-index.html">Qt 5.12.6 Reference Documentation</a></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="#the-linenumberarea-class">The LineNumberArea Class</a></li>
<li class="level1"><a href="#codeeditor-class-definition">CodeEditor Class Definition</a></li>
<li class="level1"><a href="#codeeditor-class-implementation">CodeEditor Class Implementation</a></li>
<li class="level1"><a href="#suggestions-for-extending-the-code-editor">Suggestions for Extending the Code Editor</a></li>
</ul>
</div>
<div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">Code Editor Example</h1>
<span class="subtitle"></span>
<!-- $$$widgets/codeeditor-brief -->
<p>The Code Editor example shows how to create a simple editor that has line numbers and that highlights the current line.</p>
<!-- @@@widgets/codeeditor -->
<!-- $$$widgets/codeeditor-description -->
<div class="descr"> <a name="details"></a>
<div class="border"><p class="centerAlign"><img src="images/codeeditor-example.png" alt="" /></p></div><p>As can be seen from the image, the editor displays the line numbers in an area to the left of the area for editing. The editor will highlight the line containing the cursor.</p>
<p>We implement the editor in <code>CodeEditor</code>, which is a widget that inherits <a href="qplaintextedit.html">QPlainTextEdit</a>. We keep a separate widget in <code>CodeEditor</code> (<code>LineNumberArea</code>) onto which we draw the line numbers.</p>
<p><a href="qplaintextedit.html">QPlainTextEdit</a> inherits from <a href="qabstractscrollarea.html">QAbstractScrollArea</a>, and editing takes place within its <a href="qabstractscrollarea.html#viewport">viewport()</a>'s margins. We make room for our line number area by setting the left margin of the viewport to the size we need to draw the line numbers.</p>
<p>When it comes to editing code, we prefer <a href="qplaintextedit.html">QPlainTextEdit</a> over <a href="qtextedit.html">QTextEdit</a> because it is optimized for handling plain text. See the <a href="qplaintextedit.html">QPlainTextEdit</a> class description for details.</p>
<p><a href="qplaintextedit.html">QPlainTextEdit</a> lets us add selections in addition to the selection the user can make with the mouse or keyboard. We use this functionality to highlight the current line. More on this later.</p>
<p>We will now move on to the definitions and implementations of <code>CodeEditor</code> and <code>LineNumberArea</code>. Let's start with the <code>LineNumberArea</code> class.</p>
<a name="the-linenumberarea-class"></a>
<h2 id="the-linenumberarea-class">The LineNumberArea Class</h2>
<p>We paint the line numbers on this widget, and place it over the <code>CodeEditor</code>'s <a href="qabstractscrollarea.html#viewport">viewport()</a>'s left margin area.</p>
<p>We need to use protected functions in <a href="qplaintextedit.html">QPlainTextEdit</a> while painting the area. So to keep things simple, we paint the area in the <code>CodeEditor</code> class. The area also asks the editor to calculate its size hint.</p>
<p>Note that we could simply paint the line numbers directly on the code editor, and drop the LineNumberArea class. However, the <a href="qwidget.html">QWidget</a> class helps us to <a href="qwidget.html#scroll">scroll()</a> its contents. Also, having a separate widget is the right choice if we wish to extend the editor with breakpoints or other code editor features. The widget would then help in the handling of mouse events.</p>
<pre class="cpp">

  <span class="keyword">class</span> LineNumberArea : <span class="keyword">public</span> <span class="type"><a href="qwidget.html">QWidget</a></span>
  {
  <span class="keyword">public</span>:
      LineNumberArea(CodeEditor <span class="operator">*</span>editor) : <span class="type"><a href="qwidget.html">QWidget</a></span>(editor) {
          codeEditor <span class="operator">=</span> editor;
      }

      <span class="type"><a href="../qtcore/qsize.html">QSize</a></span> sizeHint() <span class="keyword">const</span> override {
          <span class="keyword">return</span> <span class="type"><a href="../qtcore/qsize.html">QSize</a></span>(codeEditor<span class="operator">-</span><span class="operator">&gt;</span>lineNumberAreaWidth()<span class="operator">,</span> <span class="number">0</span>);
      }

  <span class="keyword">protected</span>:
      <span class="type">void</span> paintEvent(<span class="type"><a href="../qtgui/qpaintevent.html">QPaintEvent</a></span> <span class="operator">*</span>event) override {
          codeEditor<span class="operator">-</span><span class="operator">&gt;</span>lineNumberAreaPaintEvent(event);
      }

  <span class="keyword">private</span>:
      CodeEditor <span class="operator">*</span>codeEditor;
  };

</pre>
<a name="codeeditor-class-definition"></a>
<h2 id="codeeditor-class-definition">CodeEditor Class Definition</h2>
<p>Here is the code editor's class definition:</p>
<pre class="cpp">

  <span class="keyword">class</span> CodeEditor : <span class="keyword">public</span> <span class="type"><a href="qplaintextedit.html">QPlainTextEdit</a></span>
  {
      Q_OBJECT

  <span class="keyword">public</span>:
      CodeEditor(<span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>parent <span class="operator">=</span> <span class="number">0</span>);

      <span class="type">void</span> lineNumberAreaPaintEvent(<span class="type"><a href="../qtgui/qpaintevent.html">QPaintEvent</a></span> <span class="operator">*</span>event);
      <span class="type">int</span> lineNumberAreaWidth();

  <span class="keyword">protected</span>:
      <span class="type">void</span> resizeEvent(<span class="type"><a href="../qtgui/qresizeevent.html">QResizeEvent</a></span> <span class="operator">*</span>event) override;

  <span class="keyword">private</span> <span class="keyword">slots</span>:
      <span class="type">void</span> updateLineNumberAreaWidth(<span class="type">int</span> newBlockCount);
      <span class="type">void</span> highlightCurrentLine();
      <span class="type">void</span> updateLineNumberArea(<span class="keyword">const</span> <span class="type"><a href="../qtcore/qrect.html">QRect</a></span> <span class="operator">&amp;</span><span class="operator">,</span> <span class="type">int</span>);

  <span class="keyword">private</span>:
      <span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>lineNumberArea;
  };

</pre>
<p>In the editor we resize and draw the line numbers on the <code>LineNumberArea</code>. We need to do this when the number of lines in the editor changes, and when the editor's viewport() is scrolled. Of course, it is also done when the editor's size changes. We do this in <code>updateLineNumberWidth()</code> and <code>updateLineNumberArea()</code>.</p>
<p>Whenever, the cursor's position changes, we highlight the current line in <code>highlightCurrentLine()</code>.</p>
<a name="codeeditor-class-implementation"></a>
<h2 id="codeeditor-class-implementation">CodeEditor Class Implementation</h2>
<p>We will now go through the code editors implementation, starting off with the constructor.</p>
<pre class="cpp">

  CodeEditor<span class="operator">::</span>CodeEditor(<span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>parent) : <span class="type"><a href="qplaintextedit.html">QPlainTextEdit</a></span>(parent)
  {
      lineNumberArea <span class="operator">=</span> <span class="keyword">new</span> LineNumberArea(<span class="keyword">this</span>);

      connect(<span class="keyword">this</span><span class="operator">,</span> SIGNAL(blockCountChanged(<span class="type">int</span>))<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(updateLineNumberAreaWidth(<span class="type">int</span>)));
      connect(<span class="keyword">this</span><span class="operator">,</span> SIGNAL(updateRequest(<span class="type"><a href="../qtcore/qrect.html">QRect</a></span><span class="operator">,</span><span class="type">int</span>))<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(updateLineNumberArea(<span class="type"><a href="../qtcore/qrect.html">QRect</a></span><span class="operator">,</span><span class="type">int</span>)));
      connect(<span class="keyword">this</span><span class="operator">,</span> SIGNAL(cursorPositionChanged())<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(highlightCurrentLine()));

      updateLineNumberAreaWidth(<span class="number">0</span>);
      highlightCurrentLine();
  }

</pre>
<p>In the constructor we connect our slots to signals in <a href="qplaintextedit.html">QPlainTextEdit</a>. It is necessary to calculate the line number area width and highlight the first line when the editor is created.</p>
<pre class="cpp">

  <span class="type">int</span> CodeEditor<span class="operator">::</span>lineNumberAreaWidth()
  {
      <span class="type">int</span> digits <span class="operator">=</span> <span class="number">1</span>;
      <span class="type">int</span> max <span class="operator">=</span> <a href="../qtcore/qtglobal.html#qMax">qMax</a>(<span class="number">1</span><span class="operator">,</span> blockCount());
      <span class="keyword">while</span> (max <span class="operator">&gt;</span><span class="operator">=</span> <span class="number">10</span>) {
          max <span class="operator">/</span><span class="operator">=</span> <span class="number">10</span>;
          <span class="operator">+</span><span class="operator">+</span>digits;
      }

      <span class="type">int</span> space <span class="operator">=</span> <span class="number">3</span> <span class="operator">+</span> fontMetrics()<span class="operator">.</span>horizontalAdvance(QLatin1Char(<span class="char">'9'</span>)) <span class="operator">*</span> digits;

      <span class="keyword">return</span> space;
  }

</pre>
<p>The <code>lineNumberAreaWidth()</code> function calculates the width of the <code>LineNumberArea</code> widget. We take the number of digits in the last line of the editor and multiply that with the maximum width of a digit.</p>
<pre class="cpp">

  <span class="type">void</span> CodeEditor<span class="operator">::</span>updateLineNumberAreaWidth(<span class="type">int</span> <span class="comment">/* newBlockCount */</span>)
  {
      setViewportMargins(lineNumberAreaWidth()<span class="operator">,</span> <span class="number">0</span><span class="operator">,</span> <span class="number">0</span><span class="operator">,</span> <span class="number">0</span>);
  }

</pre>
<p>When we update the width of the line number area, we simply call <a href="qabstractscrollarea.html#setViewportMargins">QAbstractScrollArea::setViewportMargins</a>().</p>
<pre class="cpp">

  <span class="type">void</span> CodeEditor<span class="operator">::</span>updateLineNumberArea(<span class="keyword">const</span> <span class="type"><a href="../qtcore/qrect.html">QRect</a></span> <span class="operator">&amp;</span>rect<span class="operator">,</span> <span class="type">int</span> dy)
  {
      <span class="keyword">if</span> (dy)
          lineNumberArea<span class="operator">-</span><span class="operator">&gt;</span>scroll(<span class="number">0</span><span class="operator">,</span> dy);
      <span class="keyword">else</span>
          lineNumberArea<span class="operator">-</span><span class="operator">&gt;</span>update(<span class="number">0</span><span class="operator">,</span> rect<span class="operator">.</span>y()<span class="operator">,</span> lineNumberArea<span class="operator">-</span><span class="operator">&gt;</span>width()<span class="operator">,</span> rect<span class="operator">.</span>height());

      <span class="keyword">if</span> (rect<span class="operator">.</span>contains(viewport()<span class="operator">-</span><span class="operator">&gt;</span>rect()))
          updateLineNumberAreaWidth(<span class="number">0</span>);
  }

</pre>
<p>This slot is invoked when the editors viewport has been scrolled. The <a href="../qtcore/qrect.html">QRect</a> given as argument is the part of the editing area that is do be updated (redrawn). <code>dy</code> holds the number of pixels the view has been scrolled vertically.</p>
<pre class="cpp">

  <span class="type">void</span> CodeEditor<span class="operator">::</span>resizeEvent(<span class="type"><a href="../qtgui/qresizeevent.html">QResizeEvent</a></span> <span class="operator">*</span>e)
  {
      <span class="type"><a href="qplaintextedit.html">QPlainTextEdit</a></span><span class="operator">::</span>resizeEvent(e);

      <span class="type"><a href="../qtcore/qrect.html">QRect</a></span> cr <span class="operator">=</span> contentsRect();
      lineNumberArea<span class="operator">-</span><span class="operator">&gt;</span>setGeometry(<span class="type"><a href="../qtcore/qrect.html">QRect</a></span>(cr<span class="operator">.</span>left()<span class="operator">,</span> cr<span class="operator">.</span>top()<span class="operator">,</span> lineNumberAreaWidth()<span class="operator">,</span> cr<span class="operator">.</span>height()));
  }

</pre>
<p>When the size of the editor changes, we also need to resize the line number area.</p>
<pre class="cpp">

  <span class="type">void</span> CodeEditor<span class="operator">::</span>highlightCurrentLine()
  {
      <span class="type"><a href="../qtcore/qlist.html">QList</a></span><span class="operator">&lt;</span><span class="type"><a href="qtextedit.html">QTextEdit</a></span><span class="operator">::</span>ExtraSelection<span class="operator">&gt;</span> extraSelections;

      <span class="keyword">if</span> (<span class="operator">!</span>isReadOnly()) {
          <span class="type"><a href="qtextedit.html">QTextEdit</a></span><span class="operator">::</span>ExtraSelection selection;

          <span class="type"><a href="../qtgui/qcolor.html">QColor</a></span> lineColor <span class="operator">=</span> <span class="type"><a href="../qtgui/qcolor.html">QColor</a></span>(<span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>yellow)<span class="operator">.</span>lighter(<span class="number">160</span>);

          selection<span class="operator">.</span>format<span class="operator">.</span>setBackground(lineColor);
          selection<span class="operator">.</span>format<span class="operator">.</span>setProperty(<span class="type"><a href="../qtgui/qtextformat.html">QTextFormat</a></span><span class="operator">::</span>FullWidthSelection<span class="operator">,</span> <span class="keyword">true</span>);
          selection<span class="operator">.</span>cursor <span class="operator">=</span> textCursor();
          selection<span class="operator">.</span>cursor<span class="operator">.</span>clearSelection();
          extraSelections<span class="operator">.</span>append(selection);
      }

      setExtraSelections(extraSelections);
  }

</pre>
<p>When the cursor position changes, we highlight the current line, i.e&#x2e;, the line containing the cursor.</p>
<p><a href="qplaintextedit.html">QPlainTextEdit</a> gives the possibility to have more than one selection at the same time. we can set the character format (<a href="../qtgui/qtextcharformat.html">QTextCharFormat</a>) of these selections. We clear the cursors selection before setting the new new QPlainTextEdit::ExtraSelection, else several lines would get highlighted when the user selects multiple lines with the mouse.</p>
<p>One sets the selection with a text cursor. When using the FullWidthSelection property, the current cursor text block (line) will be selected. If you want to select just a portion of the text block, the cursor should be moved with <a href="../qtgui/qtextcursor.html#movePosition">QTextCursor::movePosition</a>() from a position set with <a href="../qtgui/qtextcursor.html#setPosition">setPosition()</a>.</p>
<pre class="cpp">

  <span class="type">void</span> CodeEditor<span class="operator">::</span>lineNumberAreaPaintEvent(<span class="type"><a href="../qtgui/qpaintevent.html">QPaintEvent</a></span> <span class="operator">*</span>event)
  {
      <span class="type"><a href="../qtgui/qpainter.html">QPainter</a></span> painter(lineNumberArea);
      painter<span class="operator">.</span>fillRect(event<span class="operator">-</span><span class="operator">&gt;</span>rect()<span class="operator">,</span> <span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>lightGray);

</pre>
<p>The <code>lineNumberAreaPaintEvent()</code> is called from <code>LineNumberArea</code> whenever it receives a paint event. We start off by painting the widget's background.</p>
<pre class="cpp">

      <span class="type"><a href="../qtgui/qtextblock.html">QTextBlock</a></span> block <span class="operator">=</span> firstVisibleBlock();
      <span class="type">int</span> blockNumber <span class="operator">=</span> block<span class="operator">.</span>blockNumber();
      <span class="type">int</span> top <span class="operator">=</span> (<span class="type">int</span>) blockBoundingGeometry(block)<span class="operator">.</span>translated(contentOffset())<span class="operator">.</span>top();
      <span class="type">int</span> bottom <span class="operator">=</span> top <span class="operator">+</span> (<span class="type">int</span>) blockBoundingRect(block)<span class="operator">.</span>height();

</pre>
<p>We will now loop through all visible lines and paint the line numbers in the extra area for each line. Notice that in a plain text edit each line will consist of one <a href="../qtgui/qtextblock.html">QTextBlock</a>; though, if line wrapping is enabled, a line may span several rows in the text edit's viewport.</p>
<p>We get the top and bottom y-coordinate of the first text block, and adjust these values by the height of the current text block in each iteration in the loop.</p>
<pre class="cpp">

      <span class="keyword">while</span> (block<span class="operator">.</span>isValid() <span class="operator">&amp;</span><span class="operator">&amp;</span> top <span class="operator">&lt;</span><span class="operator">=</span> event<span class="operator">-</span><span class="operator">&gt;</span>rect()<span class="operator">.</span>bottom()) {
          <span class="keyword">if</span> (block<span class="operator">.</span>isVisible() <span class="operator">&amp;</span><span class="operator">&amp;</span> bottom <span class="operator">&gt;</span><span class="operator">=</span> event<span class="operator">-</span><span class="operator">&gt;</span>rect()<span class="operator">.</span>top()) {
              <span class="type"><a href="../qtcore/qstring.html">QString</a></span> number <span class="operator">=</span> <span class="type"><a href="../qtcore/qstring.html">QString</a></span><span class="operator">::</span>number(blockNumber <span class="operator">+</span> <span class="number">1</span>);
              painter<span class="operator">.</span>setPen(<span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>black);
              painter<span class="operator">.</span>drawText(<span class="number">0</span><span class="operator">,</span> top<span class="operator">,</span> lineNumberArea<span class="operator">-</span><span class="operator">&gt;</span>width()<span class="operator">,</span> fontMetrics()<span class="operator">.</span>height()<span class="operator">,</span>
                               <span class="type"><a href="../qtcore/qt.html">Qt</a></span><span class="operator">::</span>AlignRight<span class="operator">,</span> number);
          }

          block <span class="operator">=</span> block<span class="operator">.</span>next();
          top <span class="operator">=</span> bottom;
          bottom <span class="operator">=</span> top <span class="operator">+</span> (<span class="type">int</span>) blockBoundingRect(block)<span class="operator">.</span>height();
          <span class="operator">+</span><span class="operator">+</span>blockNumber;
      }
  }

</pre>
<p>Notice that we check if the block is visible in addition to check if it is in the areas viewport - a block can, for example, be hidden by a window placed over the text edit.</p>
<a name="suggestions-for-extending-the-code-editor"></a>
<h2 id="suggestions-for-extending-the-code-editor">Suggestions for Extending the Code Editor</h2>
<p>No self-respecting code editor is without a syntax highligther; the <a href="qtwidgets-richtext-syntaxhighlighter-example.html">Syntax Highlighter Example</a> shows how to create one.</p>
<p>In addition to line numbers, you can add more to the extra area, for instance, break points.</p>
<p><a href="../qtgui/qsyntaxhighlighter.html">QSyntaxHighlighter</a> gives the possibility to add user data to each text block with <a href="../qtgui/qsyntaxhighlighter.html#setCurrentBlockUserData">setCurrentBlockUserData()</a>. This can be used to implement parenthesis matching. In the <code>highlightCurrentLine()</code>, the data of the currentBlock() can be fetched with <a href="../qtgui/qtextblock.html#userData">QTextBlock::userData</a>(). Matching parentheses can be highlighted with an extra selection. The &quot;Matching Parentheses with <a href="../qtgui/qsyntaxhighlighter.html">QSyntaxHighlighter</a>&quot; article in Qt Quarterly 31 implements this. You find it here: <a href="http://doc.qt.io/archives/qq/">http://doc.qt.io/archives/qq/</a>.</p>
<p>Files:</p>
<ul>
<li><a href="qtwidgets-widgets-codeeditor-codeeditor-cpp.html">widgets/codeeditor/codeeditor.cpp</a></li>
<li><a href="qtwidgets-widgets-codeeditor-codeeditor-h.html">widgets/codeeditor/codeeditor.h</a></li>
<li><a href="qtwidgets-widgets-codeeditor-codeeditor-pro.html">widgets/codeeditor/codeeditor.pro</a></li>
<li><a href="qtwidgets-widgets-codeeditor-main-cpp.html">widgets/codeeditor/main.cpp</a></li>
</ul>
</div>
<!-- @@@widgets/codeeditor -->
        </div>
       </div>
   </div>
   </div>
</div>
<div class="footer">
   <p>
   <acronym title="Copyright">&copy;</acronym> 2019 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>