qt - QTextEdit 中的文本格式很好,就像 Qt Creator 一样

标签 qt

Qt Creator发现了一个很好的格式化操作,在一些文本周围画了一个细框(这里是一个例子,我指的是 addRow 周围的框架,黄色区域是文本查找操作的结果,它也框定了在我移动光标之前找到的位置。 .)

Enter image description here

我一直无法找到如何在 QTextEdit 中获得这种效果。我试图从 Qt Creator 源中读取信息,但它们对于不知情的搜索来说太大了......

编辑

我刚刚开始研究自定义 QTextCharAttribute,通过

class framedTextAttr : public QTextObjectInterface {...}

编辑

它正在工作:根据 my answer以下。

最佳答案

使用 QTextEdit::setExtraSelections() 突出显示文档的任意部分。 QTextEdit::ExtraSelection class是具有公共(public)成员变量的简单类,用于定义每个亮点。打造亮点,

  • 获取 QTextCursor来自 QTextEdit
  • 操纵光标,使其包含正确的文本作为选择
  • 存储光标和所需QTextCharFormatExtraSelections对象(只需赋值,不需要指针或 new )
  • 存储ExtraSelections QList 中的对象(作为值)
  • 重复以上所有你想要的亮点
  • 调用setExtraSelections()方法

  • 一些示例代码:
    #include <QtGui>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        // create QTextEdit, with lot of text in it
        QTextEdit w("Alice and Bob (and Eve). ");
        for(int i=0;i<10;++i) w.setText(w.toPlainText() + w.toPlainText());
    
        // prepare variables for highlights
        QTextCharFormat fmt;
        fmt.setUnderlineStyle(QTextCharFormat::SingleUnderline);
        fmt.setUnderlineColor(QColor(200,200,200));
        fmt.setBackground(QBrush(QColor(230,230,230)));
    
        // highlight all text in parenthesis
        QTextCursor cursor = w.textCursor();
        while( !(cursor = w.document()->find(QRegExp("\\([^)]*\\)"), cursor)).isNull()) {
            QTextEdit::ExtraSelection sel = { cursor, fmt };
            selections.append(sel);
        }
    
        // set, show, go!
        w.setExtraSelections(selections);
        w.show();
        return a.exec();
    }
    

    关于qt - QTextEdit 中的文本格式很好,就像 Qt Creator 一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19232882/

    相关文章:

    c++ - 使用 C++11 编译 ui 代码时遇到 "unable to find string literal operator"错误

    android -/usr/lib/x86_64-linux-gnu/libQt5Core.so.5 : version `Qt_5.7' not found (required by emulator64-x86)

    QT/WebKit GUI 将选定的 HTML 元素数据传递给 Qt 应用程序

    python - GTK+ Dock Panel 类视觉组件

    c++ - 如何过滤 QAbstractTableModel 模型

    javascript - 如何将 iFrame 嵌入到 QT 中?

    c++ - Qt 图像处理应用程序需要直方图小部件

    c++ - MFC 到 QT 的转换

    javascript - Angular.js,从 Angular 外部调用方法后更新 View

    c++ - 为什么文件图标在 QListView 中不可见?