【问题标题】:Can I retrieve the text color (or background color) of the character at the text cursor from QTextEdit?我可以从 QTextEdit 中检索文本光标处字符的文本颜色(或背景颜色)吗?
【发布时间】:2016-05-01 23:37:20
【问题描述】:
我有一个 QTextEdit 窗口,其中的单词和字母以多种颜色显示。我希望在处理窗口内容时能够检索文本每个部分的颜色。到目前为止,我的尝试是将整个内容保存为 html 文件,然后对其进行解析以仅提取带有颜色信息的文本。这是非常麻烦和困难的。如果我可以在光标位置检索文本的颜色,我更愿意使用 QTextCursor 处理文本。我已经搜索了合适的功能,但没有找到。
是否有函数可以检索 QTextCursor 位置的颜色(或格式)?
或者,是否有办法检索与格式信息具有相同颜色(或格式)的单词和/或字符的每个连续部分?
【问题讨论】:
标签:
linux
qt
qtextedit
text-coloring
【解决方案1】:
嗯,我找到了一种方法来做我想做的事。以下是相关代码:
QTextCursor tc = qte->textCursor();
tc.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
while(tc.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor))
{
QTextCharFormat tcf = tc.charFormat();
int bg = tcf.background().color().rgb();
int fg = tcf.foreground().color().rgb();
printf("bg=%x fg=%x\n", bg, fg);
}
欢迎任何 cmets 或改进。
[以上更正]:我原来有
QColor bg = tcf.background().color().rgb();
QColor fg = tcf.foreground().color().rgb();
但在末尾加上.rgb(),它将QColor 转换为int。