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而不会改变任何东西)
答案 0 :(得分:1)
这是你的解决方案:
使用QTextCharFormat设置Underline
和background
。
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);
}