Henkk

导航

QT----富文本操作

1.富文本主要的架构:

2. 最主要的光标切换函数moveCursor()

3.不同行显示不同的背景,相同行显示不同的字体效果如下:

 主要代码:

  QTextBlockFormat defaultFormat = ui->textBrowser->textCursor().blockFormat();
    QTextCursor cursorRoot = ui->textBrowser->textCursor();
    QTextFrameFormat frameFormat;
    frameFormat.setBackground(Qt::lightGray);                  // 设置背景颜色
//    frameFormat.setMargin(2);                                 // 设置边距
    frameFormat.setTopMargin(0);
    frameFormat.setPadding(10);                                 // 设置填衬
    frameFormat.setBorderBrush(Qt::red);
    frameFormat.setBorder(10);
    frameFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Solid); // 设置边框样式
    QTextCursor cursor = ui->textBrowser->textCursor();                  // 获取光标
    cursor.insertFrame(frameFormat);                                  // 在光标处插入框架
    cursor.insertText("sdlsdlskdl\ndskdjk");
    ui->textBrowser->moveCursor(QTextCursor::NextBlock);

    QTextFrameFormat frameFormat2;
    frameFormat.setBackground(Qt::darkBlue);                  // 设置背景颜色
    frameFormat.setMargin(0);                                 // 设置边距
    frameFormat.setPadding(0);                                 // 设置填衬
    frameFormat.setBorderBrush(Qt::yellow);
    frameFormat.setBorder(5);
    frameFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Solid); // 设置边框样式
    QTextCursor cursor2 = ui->textBrowser->textCursor();                  // 获取光标
    cursor2.insertFrame(frameFormat);                                  // 在光标处插入框架
    cursor2.insertText("sdlsdlskdl\ndskdjk");
    ui->textBrowser->moveCursor(QTextCursor::NextBlock);

    QTextCharFormat charFormat;                // 字符格式
    charFormat.setBackground(Qt::lightGray);   // 背景色
    charFormat.setForeground(Qt::blue);        // 字体颜色
    charFormat.setFont(QFont(tr("宋体"), 12, QFont::Bold, true));  // 使用宋体,12号,加粗,倾斜
    charFormat.setFontUnderline(true);         // 使用下划线
    QTextBlockFormat blockFormat;
    blockFormat.setTopMargin(0);
    blockFormat.setBackground(Qt::lightGray);
    ui->textBrowser->textCursor().insertBlock(blockFormat);                                  // 在光标处插入框架
    ui->textBrowser->textCursor().insertText("sdlsdlskdldskdjk\n", charFormat);
    charFormat.setForeground(Qt::red);        // 字体颜色
    charFormat.setFontUnderline(false);         // 使用下划
    ui->textBrowser->textCursor().insertText("sdlsdlskdldskdjk", charFormat);
    ui->textBrowser->moveCursor(QTextCursor::NextBlock);

    blockFormat.setTopMargin(5);
    blockFormat.setBackground(Qt::darkBlue);
    ui->textBrowser->textCursor().insertBlock(blockFormat);
    ui->textBrowser->insertPlainText("djskjdksjdksjdjsdsdsdsds");
    ui->textBrowser->moveCursor(QTextCursor::NextBlock);
    ui->textBrowser->textCursor().insertBlock(defaultFormat);
    qInfo() << defaultFormat.topMargin();
    ui->textBrowser->insertPlainText("123");

 

posted on 2023-04-19 22:59  Henkk  阅读(124)  评论(0编辑  收藏  举报