tl;博士:
QPlainTextEdit::appendPlainText(QString)
将换行符附加到我的文本小部件。 QPlainTextEdit::insertPlainText(QString)
似乎不受setCurrentCharFormat()
.
QTextCharFormat
有没有办法在不插入换行符的情况下在收听当前时附加文本
细节
我有一个“终端”样式的小部件,它从子进程的标准输出中获取文本并将其显示在QPlainTextEdit
.
在我有颜色内容之前,我可以简单地这样做:
void ProcessWidget::appendText(QString text)
{
m_textedit->appendPlainText(text);
}
'\033'
颜色使用转义字符后跟颜色出现在文本中。我可以检测颜色并适当地设置调色板:
void ProcessWidget::appendText(QString text)
{
Qt::GlobalColor colour = GetColour(text);
QTextCharFormat tf = m_textedit->currentCharFormat();
tf.setForeground(QBrush(colour));
m_textedit->setCurrentCharFormat(tf);
m_textedit->appendPlainText(text);
}
如果每行只有一种颜色,则此方法有效,但如果我的颜色在每行中途发生变化,那么我需要更疯狂一点:
std::map<QString, Qt::GlobalColor> m_colours;
QPlainTextEdit* m_textedit;
...
void ProcessWidget::AppendText(QString text)
{
while(true)
{
int iColour = text.indexOf('\033');
if (iColour == -1)
break;
QString pretext = text.mid(0, iColour);
if (!pretext.isEmpty())
{
m_textedit->appendPlainText(pretext);
}
text.remove(0, iColour);
for (auto pair : m_colours)
{
if ( text.startsWith(pair.first) )
{
QTextCharFormat tf = m_textedit->currentCharFormat();
tf.setForeground(QBrush(pair.second));
m_textedit->setCurrentCharFormat(tf);
text.remove(0, pair.first.size());
break;
}
}
}
if (!text.isEmpty())
{
m_textedit->appendPlainText(text);
}
}
但是,因为我使用appendPlainText()
,所以找到的每种新颜色都会给我一个新行。
我尝试替换appendPlainText()
为:
m_textedit->moveCursor (QTextCursor::End);
m_textedit->insertPlainText(text);
m_textedit->moveCursor (QTextCursor::End);
然后'\n'
在最后添加。但在那种情况下,我不再有任何颜色了。我也试过appendHtml()
,但这似乎没有什么不同。