본문 바로가기

Qt

QT TextEdit Block & Char Formatting

QT Text에서 block 및 character별로 format을 지정할 수 있다.

거기에 중심이 있는 것이 

QTextCursor와 QCharTextFormat, QBlockTextFormat 이다.


Block은 문단이라 보면 되고 커서가 있는 위치에서의 문단의 속성을 변경시킨다.

character는 말 그대로 각각의 문자를 뜻한다.


우선 기본적으로 알아야할 개념이 있다.

QTextCursor에서 anchor와 position 두가지이다 

position은 커서가 있는 위치를 말하고 anchor는 마치 

마우스로 text를 드레그해서 선택영역을 만들었을 때처럼

선택영역의 시작이 되는 시점을 말한다.

예를 들어 This의 T 앞에서 시작해 text의 끝까지 선택했다면 

아래와 같이 anchor와 position이 위치된다.

[Anchor]This is a sample text[Position]


이것을 기반으로 


QTextCursor cursor(this->textCursor());
QTextCharFormat charFormat = this->textCursor().charFormat();
charFormat.setFont(QFont("Times", 15, QFont::Bold));
charFormat.setBackground(QBrush(Qt::CrossPattern));

cursor.setPosition(0);
cursor.setPosition(3, QTextCursor::KeepAnchor);
cursor.setCharFormat(charFormat);

QTextBlockFormat blockFormat = cursor.blockFormat();
blockFormat.setBackground(QColor(255, 255, 0, 50));
blockFormat.setNonBreakableLines(false);
blockFormat.setPageBreakPolicy(QTextFormat::PageBreak_AlwaysBefore);
cursor.setBlockFormat(blockFormat);


다음과 같이 구성할 수도 있을 것이다.

위의 코드는 먼저 현재 cursor및 charformat을 받아 폰트 및 배경색을 지정하고 

setPosition함수로 선택영역을 만들고 format을 지정한다.

그리고 블럭 전체의 format변경을 위해 blockformat을 변경하여 적용한다.


다시한번 기억할 것은 

1. 영역 선택

2. Character format 변경

3. Block 변경은 커서 위치