繁体   English   中英

如何在不使用当前段落样式的情况下将 append 转换为 QTextEdit

[英]How to append to QTextEdit without using the current paragraph style

使用myQTextEdit.append()时,插入文本的样式如下(Qt 5.14 文档):

"附加的新段落将具有与当前段落相同的字符格式和块格式,由 cursor 的 position 确定。 "

但是,我会发现能够使用中性样式的 append 文本很方便。

导致我的问题的原因是:我有一个 QTextEdit 形式的日志 window ,其中我有 append 文本(大部分是中性的,但某些元素可能是彩色的,等等)。 由于它用于日志目的,因此 QTextEdit 是只读的,并且始终在末尾添加文本元素( append() )。 只要用户从不点击文本就可以了。 当点击 QTextEdit 的一部分时,cursor position 会发生变化。 这对 position 来说不是问题,因为我使用了在末尾插入文本的 append(),即使 cursor 在其他地方也是如此。 但是,如果用户单击了具有非中性样式的内容,则随后附加的文本也将具有这种样式,这是不可取的。

对我来说有趣的是阻止 cursor 以便用户不能篡改 styles 或 append 而不基于当前段落的样式。

除了继承 QTextEdit 之外,有没有办法改变这种行为?

如前所述,我可以在执行任何 append() 之前检查 cursor position (并在文档末尾设置 cursor 如果它已被移动)但如果它存在,我会更喜欢“全局”解决方案。

我试图在MCVE中重现 OP 描述的内容:

// Qt header:
#include <QtWidgets>

// main application
int main(int argc, char **argv)
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  QApplication app(argc, argv);
  // setup GUI
  QTextEdit qTextEdit;
  qTextEdit.show();
  // populate text editor
  qTextEdit.append(QString::fromUtf8(
    "<p>This is some text...</p>"
    "<p style='color: red'>...followed by more red text...</p>"
    "<p style='color: blue; font-weight: bold'>...followed by more fat blue text.</p>"));
  // test QTextEdit::append() like described by OP:
  qTextEdit.setTextCursor(QTextCursor(qTextEdit.document()->findBlockByNumber(1)));
  qTextEdit.append("TEST. (Reproduce what OP described.)");
  qTextEdit.append("<p>TEST. (A possible fix.)</p>");
  // runtime loop
  return app.exec();
}

Output:

MCVE 的快照

因此,一个可能的解决方法是向 append 提供带有标记的文本。

如果它只是原始文本,最简单的解决方案是将其包装在"<p>""</p>"中。

顺便提一句。 如果它只是原始文本,我建议根据Supported HTML Subset进行一些额外的调整以使其正确 HTML 。 即,我将搜索并替换通常的 XML 元字符,就像我在对SO 的回答中所做的那样: qt plaintextedit change message color

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM