将自定义HTML类特性添加到QTextEdit中的选定块

Add custom HTML class property to selected block in a QTextEdit

本文关键字:QTextEdit 添加 HTML 自定义      更新时间:2023-10-16

我不是Qt的新手,但我找不到如何在QTextEdit中向所选块添加自定义css类。

据我所知,格式被这样的代码改变了:

QTextCursor cursor = textEdit->textCursor();
QTextBlockFormat bfmt;
// Apply format changes
cursor.setBlockFormat(bfmt);

当我这样做时,生成的HTML代码会创建一个带有内联样式的span,但我想要的是插入css类:

<SPAN class='myclass'>text</span>

我在QTextBlockFormat中缺少一个函数来设置文本的css类。

您应该能够通过手动将<span style="">标记添加到所选文本中来模拟这种行为:

QString oldText = cursor.selectedText();
// not the best way to concat three strings, but for example only...
cursor.insertHtml(QString("<span class="%1">%2</span>").arg("myclass").arg(oldText));

selectedText()将返回当前选择的文本,insertHtml()将在光标开始处插入新文本,删除当前选择(如果有的话)。