代码环境
Qt5.12.9
QTextEdit 实现注释功能
- 单行注释
- 多行注释
- 反注释
代码
void AnnotationCode()
{
char32_t t = 0x2029; // 2029表示unicode换行符
QChar br(t); // 初始化一个换行符
QTextDocument* pDoc = ui->textEdit->document();
QTextCursor textCursor(pDoc);
// 获取选中字符串
QString selectStr = ui->textEdit->textCursor().selectedText();
// 将光标移动到选中初始位置
textCursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor, textCursor.position() - selectStr.count());
if (selectStr.count() > 0) // 多行注释
{
// 根据第一个字符判断是注释还是反注释
if (selectStr.at(0) == '#') // 反注释
{
selectStr.remove(0, 1);
for (int i = 0; i < selectStr