这个例子其实很多没看懂的,先写点看懂的部分做下笔记~~特别是QPlainTextEditor的每一行的高度是怎么与显示行号的widget对应的这么合理的。
CodeEditor Example由两个类组成
LineNumberArea + CodeEdit
CodeEdit负责文字输入,LineNumberArea则负责行数的显示。两者之间组成关系是
We paint the line numbers on this widget(LineNumberArea), and place it over the CodeEditor's viewport()'s left margin area.
如果我们setViewportMargins()设定了margin,LineNumberArea的parent又是CodeEdit,那么LineNumberArea自动生成在margin上?
在以下三种情况下,需要draw LineNumberArea(只有这个想清楚了才能写好信号和槽阿~~我是没想明白。。。)
1.when the number of lines in the editor changes
2.when the editor's viewport() is scrolled
3.Of course, it is also done when the editor's size changes
先说下viewport
viewport部分就是主窗口用于输入的,四周是verticalScrollBar或者horizontalScrollBar。当然也可以通过setViewportMargins()来在viewport周围先加一些空白~~
具体的Qt文档里这么介绍的:
The QAbstractScrollArea widget provides a scrolling area with on-demand scroll bars.

QAbstractScrollArea is a low-level abstraction of a scrolling area. The area provides a central widget called the viewport, in which the contents of the area is to be scrolled (i.e, the visible parts of the contents are rendered in the viewport).

Next to the viewport is a vertical scroll bar, and below is a horizontal scroll bar. When all of the area contents fits in the viewport, each scroll bar can be either visible or hidden depending on the scroll bar's Qt::ScrollBarPolicy. When a scroll bar is hidden, the viewport expands in order to cover all available space. When a scroll bar becomes visible again, the viewport shrinks in order to make room for the scroll bar.

It is possible to reserve a margin area around the viewport, see setViewportMargins(). The feature is mostly used to place a QHeaderView widget above or beside the scrolling area. Subclasses of QAbstractScrollArea should implement margins.1

1.
fontMetrics().width(QLatin1Char('9'))
返回只有一个字符‘9’时的合理宽度~~
2.
void QAbstractScrollArea::setViewportMargins ( int left, int top, int right, int bottom )
这个函数一直弄混了,该函数实际上是创建了四个margin
setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
例如该语句即是在左边创建一个margin~~虽然只传进了一个int值,但viewport周围的margin是环绕整个viewport的,所以另一条边是固定大小的(早想到这点就不会看不明白了。。。)