QT----富文本操作
1.富文本主要的架构:
2. 最主要的光标切换函数moveCursor()
3.不同行显示不同的背景,相同行显示不同的字体效果如下:
主要代码:
QTextBlockFormat defaultFormat = ui->textBrowser->textCursor().blockFormat(); QTextCursor cursorRoot = ui->textBrowser->textCursor(); QTextFrameFormat frameFormat; frameFormat.setBackground(Qt::lightGray); // 设置背景颜色 // frameFormat.setMargin(2); // 设置边距 frameFormat.setTopMargin(0); frameFormat.setPadding(10); // 设置填衬 frameFormat.setBorderBrush(Qt::red); frameFormat.setBorder(10); frameFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Solid); // 设置边框样式 QTextCursor cursor = ui->textBrowser->textCursor(); // 获取光标 cursor.insertFrame(frameFormat); // 在光标处插入框架 cursor.insertText("sdlsdlskdl\ndskdjk"); ui->textBrowser->moveCursor(QTextCursor::NextBlock); QTextFrameFormat frameFormat2; frameFormat.setBackground(Qt::darkBlue); // 设置背景颜色 frameFormat.setMargin(0); // 设置边距 frameFormat.setPadding(0); // 设置填衬 frameFormat.setBorderBrush(Qt::yellow); frameFormat.setBorder(5); frameFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Solid); // 设置边框样式 QTextCursor cursor2 = ui->textBrowser->textCursor(); // 获取光标 cursor2.insertFrame(frameFormat); // 在光标处插入框架 cursor2.insertText("sdlsdlskdl\ndskdjk"); ui->textBrowser->moveCursor(QTextCursor::NextBlock); QTextCharFormat charFormat; // 字符格式 charFormat.setBackground(Qt::lightGray); // 背景色 charFormat.setForeground(Qt::blue); // 字体颜色 charFormat.setFont(QFont(tr("宋体"), 12, QFont::Bold, true)); // 使用宋体,12号,加粗,倾斜 charFormat.setFontUnderline(true); // 使用下划线 QTextBlockFormat blockFormat; blockFormat.setTopMargin(0); blockFormat.setBackground(Qt::lightGray); ui->textBrowser->textCursor().insertBlock(blockFormat); // 在光标处插入框架 ui->textBrowser->textCursor().insertText("sdlsdlskdldskdjk\n", charFormat); charFormat.setForeground(Qt::red); // 字体颜色 charFormat.setFontUnderline(false); // 使用下划 ui->textBrowser->textCursor().insertText("sdlsdlskdldskdjk", charFormat); ui->textBrowser->moveCursor(QTextCursor::NextBlock); blockFormat.setTopMargin(5); blockFormat.setBackground(Qt::darkBlue); ui->textBrowser->textCursor().insertBlock(blockFormat); ui->textBrowser->insertPlainText("djskjdksjdksjdjsdsdsdsds"); ui->textBrowser->moveCursor(QTextCursor::NextBlock); ui->textBrowser->textCursor().insertBlock(defaultFormat); qInfo() << defaultFormat.topMargin(); ui->textBrowser->insertPlainText("123");
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本