qt - QPlainTextEdit : different char format for part of text

标签 qt qtextcursor

在扫描了几个例子后我没能解决这个问题: 我为此创建了一个测试,它有一个简单的 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);
}

image

关于qt - QPlainTextEdit : different char format for part of text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46929843/

相关文章:

c++ - 为什么 cursor.clearselection() 在此示例中不起作用?

android - 向 Android 应用程序添加额外文件

c++ - 如何在 C++ 的精确帧中设置 QQuickItem 位置?

c++ - 检查 OSX 是否采用 24 小时制

c++ - 将项目小部件宽度(列表内容)调整为父 QListWidget 宽度

c++ - 信号/槽连接总数?

c++ - QPlainTextEdit 忽略大部分文本 block 格式

python-2.7 - 如何在 PyQt4 中更改 QTextEdit 中所有内容的字体大小?