QTextEdit更改单个段落/块的字体

c – QTextEdit更改单个段落/块的字体

2019-05-15
使用QTextEdit,我需要单独更改每个段落的字体属性.这类似于当用户从菜单中选择样式(而不是特定格式)时,有多少文字处理器更改段落的字体.

理想情况下,我想在布局和渲染之前将QTextCharFormat(或等效物)应用于块(段落),但我希望文本中不会插入任何字体属性,因为我不希望这样文件中的信息,但我需要保留用户可能设置为段落中的单词的任何粗体/斜体/下划线属性(我打算将所需信息保存在QTextBlock :: userData中).但是,我无法想象我需要插入一个函数来执行此任务.

我想我无法从QTextBlock和QTextCursor更改段落的QTextCharFormat,因为这仅适用于新块,它不会影响具有现有文本的块.

我检查了QTextLayout,但我不认为我的答案在那里.

我几天来一直在寻找这个问题的解决方案.对于任何指向正确方向的人,我都会非常优雅.

我有多年的C经验,但我对Qt有些新意.使用Qt 4.8.

编辑:

我在上面强调了(粗体)我正在尝试做的一个重要部分.换句话说,我真正想做的是能够在显示之前将字体属性应用于文本块(可能是临时副本).我完全习惯于为了实现这个目标而导出和修改(甚至重新实现)我需要的任何类,但我需要指出正确的方向,以确定我实际需要改变什么.作为最后的手段,我还可以直接修改一些Qt类,如果这对于任务是必要的,但是我还需要知道我需要触摸哪个类.我希望这更清楚.我发现很难解释这一点,但不允许告诉你应用程序将完全做什么.

 
[必需的图书馆]
#include <QTextEdit>    // not needed if using the designer

#include <QTextDocument>
#include <QTextBlock>
#include <QTextCursor>

[战略]

QTextDocument

我需要它来管理块.功能QTextDocument::findBlockByNumber非常方便找到以前的块,我认为这就是你所追求的.

QTextBlock

块文本的容器.一个美好而方便的课程.

QTextCursor

令人惊讶的是,QTextBlock类中没有格式设置器.因此,我使用QTextCursor作为解决方法,因为此类中有四个格式设置器.

[格式代码]

// For block management
QTextDocument *doc = new QTextDocument(this);
ui->textEdit->setDocument(doc);  // from QTextEdit created by the Designer
//-------------------------------------------------
// Locate the 1st block
QTextBlock block = doc->findBlockByNumber(0);

// Initiate a copy of cursor on the block
// Notice: it won't change any cursor behavior of the text editor, since it 
//         just another copy of cursor, and it's "invisible" from the editor.
QTextCursor cursor(block);

// Set background color
QTextBlockFormat blockFormat = cursor.blockFormat();
blockFormat.setBackground(QColor(Qt::yellow));
cursor.setBlockFormat(blockFormat);

// Set font
for (QTextBlock::iterator it = cursor.block().begin(); !(it.atEnd()); ++it)
{
    QTextCharFormat charFormat = it.fragment().charFormat();
    charFormat.setFont(QFont("Times", 15, QFont::Bold));

    QTextCursor tempCursor = cursor;
    tempCursor.setPosition(it.fragment().position());
    tempCursor.setPosition(it.fragment().position() + it.fragment().length(), QTextCursor::KeepAnchor);
    tempCursor.setCharFormat(charFormat);
}

参考:
How to change current line format in QTextEdit without selection?

[DEMO]

构建环境:Qt 4.8 MSVC2010编译器Windows 7 32位

该演示仅用于显示在特定块上设置格式的概念.

纯文本输入

格式1(注意它不会打扰视图中的当前光标)

格式2

原文地址:https://www.cnblogs.com/lehoho/p/11453471.html