-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinenumberarea.cpp
70 lines (57 loc) · 2.19 KB
/
linenumberarea.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include "linenumberarea.h"
LineNumberArea::LineNumberArea(QTextEdit *editor)
: QWidget{editor}
, textEdit(editor)
{
if (editor)
this->setPalette(textEdit->palette());
}
QSize LineNumberArea::sizeHint() const
{
return QSize(lineNumberAreaWidth(), textEdit->height());;
}
void LineNumberArea::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.fillRect(event->rect(), palette().base().color().darker(64));
QTextBlock block = textEdit->document()->begin();
int lineNumber = 1;
int top = static_cast<int>(textEdit->document()->documentLayout()->blockBoundingRect(block).translated(0, -textEdit->verticalScrollBar()->value()).top());
int bottom = top + static_cast<int>(textEdit->document()->documentLayout()->blockBoundingRect(block).height());
while (block.isValid() && top <= event->rect().bottom())
{
if (block.isVisible() && bottom >= event->rect().top())
{
QTextLayout *layout = block.layout();
const int lineCount = layout->lineCount();
for (int i = 0; i < lineCount; ++i)
{
QTextLine line = layout->lineAt(i);
int lineTop = static_cast<int>(line.y()) + top;
int lineBottom = lineTop + static_cast<int>(line.height());
if (lineTop >= event->rect().top() && lineBottom <= event->rect().bottom())
{
QString number = QString::number(lineNumber);
painter.setPen(textEdit->palette().text().color());
painter.drawText(0, lineTop, width(), textEdit->fontMetrics().height(), Qt::AlignCenter, number);
++lineNumber;
}
}
}
block = block.next();
top = bottom;
bottom = top + static_cast<int>(textEdit->document()->documentLayout()->blockBoundingRect(block).height());
}
}
int LineNumberArea::lineNumberAreaWidth() const
{
int digits = 1;
int max = qMax(1, textEdit->document()->blockCount());
while (max >= 10)
{
max /= 10;
++digits;
}
int space = 3 + textEdit->fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits;
return space;
}