41#include <QPlainTextEdit>
50 lineNumberArea =
new LineNumberArea(
this);
52 connect(
this, SIGNAL(blockCountChanged(
int)),
this, SLOT(updateLineNumberAreaWidth(
int)));
53 connect(
this, SIGNAL(updateRequest(QRect,
int)),
this, SLOT(updateLineNumberArea(QRect,
int)));
54 connect(
this, SIGNAL(cursorPositionChanged()),
this, SLOT(highlightCurrentLine()));
56 QFont font(QStringLiteral(
"Monospace"));
57 font.setStyleHint(QFont::TypeWriter);
60 updateLineNumberAreaWidth(0);
61 highlightCurrentLine();
69 int max = qMax(1, blockCount());
75 const int space = 3 + (fontMetrics().horizontalAdvance(QLatin1Char(
'9')) * digits);
82void CodeEditor::updateLineNumberAreaWidth(
int )
89void CodeEditor::updateLineNumberArea(QRect rect,
int dy)
92 lineNumberArea->scroll(0, dy);
94 lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
96 if (rect.contains(viewport()->rect()))
97 updateLineNumberAreaWidth(0);
104 QPlainTextEdit::resizeEvent(event);
106 const QRect cr = contentsRect();
107 lineNumberArea->setGeometry(QRect(cr.left(), cr.top(),
lineNumberAreaWidth(), cr.height()));
116void CodeEditor::highlightCurrentLine()
118 QList<QTextEdit::ExtraSelection> extraSelections;
121 QTextEdit::ExtraSelection selection;
123 const QColor lineColor = QColor(Qt::yellow).lighter(160);
125 selection.format.setBackground(lineColor);
126 selection.format.setProperty(QTextFormat::FullWidthSelection,
true);
127 selection.cursor = textCursor();
128 selection.cursor.clearSelection();
129 extraSelections.append(selection);
132 setExtraSelections(extraSelections);
139 QPainter painter(lineNumberArea);
140 painter.fillRect(event->rect(), Qt::lightGray);
143 QTextBlock block = firstVisibleBlock();
144 int blockNumber = block.blockNumber();
145 int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
146 int bottom = top + (int) blockBoundingRect(block).height();
148 while (block.isValid() && top <=
event->rect().bottom()) {
149 if (block.isVisible() && bottom >=
event->rect().top()) {
150 const QString number = QString::number(blockNumber + 1);
151 painter.setPen(Qt::black);
152 painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(),
153 Qt::AlignRight, number);
156 block = block.next();
158 bottom = top + (int) blockBoundingRect(block).height();
void focusOutEvent(QFocusEvent *event) override
CodeEditor(QWidget *parent=nullptr)
void lineNumberAreaPaintEvent(QPaintEvent *event)
void resizeEvent(QResizeEvent *event) override
void editingFinished(QString)
int lineNumberAreaWidth()