在文本编辑器Text Edit中选择文本不用提,这里说的是用程序来控制选择与修改。
其实也很简单,只不过在知道之前搜索半天都搞不清楚。
首先要理解Qt的概念。
- 光标,QTextCursor,就是编辑器当前光标的信息,光标位置只是其中之一,而且位置信息藏得很深。
- 块,QTextBlock,先理解块就是文本中的段。
下面的代码是程序控制选择文本并格式化它。
QTextCursor tc = ui->te_main->textCursor(); //当前光标
QTextBlock blk = tc.block(); //光标下的块,即段
QString ln = blk.text(); //块文本
//程序控制选择
tc.setPosition(blk.begin().fragment().position());
tc.setPosition(blk.end().fragment().position(),QTextCursor::KeepAnchor);
//把选择的文本格式化
QTextCharFormat fmt;
fmt.setForeground(Qt::red);
tc.setCharFormat(fmt);