在扫描了几个例子后我没能解决这个问题:
我为此创建了一个测试,它有一个简单的 MainWindow 和一个包含一些文本的 QPlainTextEdit
。在触发器上,我希望部分文本为红色并带有下划线。但那永远不会发生。
问候
我的代码:
void MainWindow::on_actionTest_triggered()
{
QTextCursor cur = ui.plainTextEdit->textCursor();
cur.setPosition(49);
QTextCharFormat oldFormat = cur.charFormat();
QTextCharFormat newFormat = oldFormat;
newFormat.setForeground(Qt::darkRed);
newFormat.setUnderlineColor(Qt::darkRed);
newFormat.setUnderlineStyle(QTextCharFormat::WaveUnderline);
newFormat.setFontUnderline(true);
cur.setCharFormat(newFormat);
cur.setPosition(cur.position()+11);
cur.setCharFormat(oldFormat);
ui.plainTextEdit->setTextCursor(cur);
}
改用 QTextEdit 不会改变任何东西)
最佳答案
这是您的解决方案:
使用 QTextCharFormat设置下划线
和背景
。
void MainWindow::on_pushButton_clicked()
{
int begin = 30; //begin highlight
int end = 40; //end highlight
QTextCharFormat fmt;
fmt.setBackground(Qt::red); // set color red
fmt.setUnderlineStyle(QTextCharFormat::SingleUnderline); //set underline
QTextCursor cursor(ui->plainTextEdit->document());
cursor.setPosition(begin, QTextCursor::MoveAnchor);
cursor.setPosition(end, QTextCursor::KeepAnchor);
cursor.setCharFormat(fmt);
}
关于qt - QPlainTextEdit : different char format for part of text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46929843/