[Qt-interest] Code Editor PlainTextEdit Modified

Raja Sekharan websweetweb at gmail.com
Thu Mar 19 17:36:43 CET 2009


Hi,

The code editor example that shows how to create a text editor with line numbers and comes with the QtAssistant help files can be made suitable for all situations by a simple modification to the function

  void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
in codeeditor.cpp.

Here's the new function:

  void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
   {
       QPainter painter(lineNumberArea);
       >>QPoint origin(0,0);
       >>QPoint globalStart  = this->mapToGlobal(origin);
       >>QPoint globalEnd(globalStart.x()+this->width(),globalStart.y()+this->height());
       >>QRect theRect(origin,globalEnd);
       >>painter.fillRect(theRect, Qt::lightGray);


       QTextBlock block = firstVisibleBlock();
       int blockNumber = block.blockNumber();
       int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
       int bottom = top + (int) blockBoundingRect(block).height();

       while (block.isValid() && top <= event->rect().bottom()) {
           if (block.isVisible() && bottom >= event->rect().top()) {
               QString number = QString::number(blockNumber + 1);
               painter.setPen(Qt::black);
               painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(),
                                Qt::AlignRight, number);
           }

           block = block.next();
           top = bottom;
           bottom = top + (int) blockBoundingRect(block).height();
           ++blockNumber;
       }
   }
The lines with the >> are the modified lines. It simply finds the global position of the code editor and positions the line numbers there. You can use this even if the text editor is movable within the window like using inside a QMdiSubWindow.

Raja Sekharan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20090319/88430db7/attachment.html 


More information about the Qt-interest-old mailing list