Qt-快速上手-QTextCursor

QTextCursor

头文件:#include <QTextCursor>

QTextCursor:不是控件 ,是操作QTextDocument文档的光标工具类。配合QTextEdit / QPlainTextEdit使用,用来移动光标、选中文本、插入文字、删除文本。

QTextEdit 获取光标:textEdit->textCursor();修改完需要 textEdit->setTextCursor(cursor) 回写生效。

常用对象和方法

c++ 复制代码
/**
 * @class QTextCursor
 * @brief 用于遍历和编辑QTextDocument文档内容的光标类,类似文本编辑器里的光标
 *
 * QTextCursor提供对QTextDocument的程序化编辑能力:移动光标、选中文本、插入文字/图片/表格、删除内容、获取块信息。
 * 它操作的是文档副本,修改光标属性不会立刻刷新控件,需要作用到QTextDocument才生效。
 *
 * @note 重要:QTextCursor本身不绑定QTextEdit控件;QTextEdit::textCursor()获取控件当前光标,setCursor()设置回去才能界面生效。
 *
 * 示例基础用法:
 * @code
 * QTextDocument doc;
 * QTextCursor cursor(&doc);
 * cursor.insertText("hello world");
 * @endcode
 */
class QTextCursor
{
public:
    //--------------------------------------------------------------------------
    // 构造函数
    //--------------------------------------------------------------------------
    /**
     * @brief 默认构造,构造无效光标,需要后续绑定文档
     */
    QTextCursor();

    /**
     * @brief 使用文档构造光标,光标默认位于文档开头
     * @param document 目标QTextDocument对象指针
     */
    explicit QTextCursor(QTextDocument *document);

    /**
     * @brief 从QTextFrame构造光标
     * @param frame 文本框架
     */
    explicit QTextCursor(QTextFrame *frame);

    /**
     * @brief 拷贝构造
     * @param other 另一个QTextCursor实例
     */
    QTextCursor(const QTextCursor &other);

    //--------------------------------------------------------------------------
    // 光标位置 & 选区相关
    //--------------------------------------------------------------------------
    /**
     * @brief position 获取光标当前绝对位置(文档内字符偏移索引,从0开始)
     * @return int 当前字符索引位置
     */
    int position() const;

    /**
     * @brief setPosition 设置光标绝对位置
     * @param pos 目标字符偏移
     * @param mode 移动模式:MoveAnchor(只移动锚点,不形成选区) / KeepAnchor(保持锚点,形成选区)
     *
     * @par 模式说明
     * - QTextCursor::MoveAnchor:移动光标,取消选中
     * - QTextCursor::KeepAnchor:移动光标,锚点不动,生成选中区域
     */
    void setPosition(int pos, MoveMode mode = MoveAnchor);

    /**
     * @brief anchor 返回选区锚点位置。选区 = [anchor(), position()]
     * @return int 锚点偏移
     */
    int anchor() const;

    /**
     * @brief hasSelection 判断是否存在选中文本
     * @return true 有选区;false无选区
     */
    bool hasSelection() const;

    /**
     * @brief selectionStart 获取选区起始位置
     * @return int 选区开始偏移
     */
    int selectionStart() const;

    /**
     * @brief selectionEnd 获取选区结束位置
     * @return int 选区结束偏移
     */
    int selectionEnd() const;

    /**
     * @brief selectedText 获取选区内的文本内容(去除格式)
     * @return QString 选中的纯文本
     */
    QString selectedText() const;

    /**
     * @brief clearSelection 清除选区,锚点与光标合并,不移动光标位置
     */
    void clearSelection();

    //--------------------------------------------------------------------------
    // 移动光标 movePosition() 核心枚举 MoveOperation
    //--------------------------------------------------------------------------
    /**
     * @brief movePosition 移动光标,支持多种移动语义
     * @param op 移动操作枚举
     * @param mode MoveAnchor / KeepAnchor
     * @param n 移动步数,默认1
     * @return bool 是否移动成功;到达文档边界返回false
     *
     * MoveOperation常用枚举值:
     * - Start: 跳到文档开头
     * - End: 跳到文档末尾
     * - StartOfLine: 行首
     * - EndOfLine: 行尾
     * - PreviousCharacter: 向前一个字符
     * - NextCharacter: 向后一个字符
     * - PreviousWord: 上一个单词
     * - NextWord: 下一个单词
     * - PreviousBlock: 上一个文本块(段落)
     * - NextBlock: 下一个文本块(段落)
     */
    bool movePosition(MoveOperation op, MoveMode mode = MoveAnchor, int n = 1);

    //--------------------------------------------------------------------------
    // 插入内容
    //--------------------------------------------------------------------------
    /**
     * @brief insertText 在光标位置插入纯文本
     * @param text 需要插入的字符串
     * @param charFormat 可选字符格式,控制字体颜色大小等
     */
    void insertText(const QString &text, const QTextCharFormat &charFormat = QTextCharFormat());

    /**
     * @brief insertHtml 插入HTML富文本
     * @param html html片段字符串
     */
    void insertHtml(const QString &html);

    /**
     * @brief insertBlock 插入新段落块
     * @param blockFormat 段落格式
     * @param charFormat 块内字符格式
     */
    void insertBlock(const QTextBlockFormat &blockFormat = QTextBlockFormat(),
                     const QTextCharFormat &charFormat = QTextCharFormat());

    /**
     * @brief insertImage 插入图片
     * @param imageFormat QTextImageFormat 设置图片路径、宽高
     */
    void insertImage(const QTextImageFormat &imageFormat);

    /**
     * @brief insertTable 插入表格
     * @param rows 行数
     * @param cols 列数
     * @param tableFormat 表格格式
     * @return QTextTable* 返回新建表格对象指针
     */
    QTextTable* insertTable(int rows, int cols, const QTextTableFormat &tableFormat = QTextTableFormat());

    //--------------------------------------------------------------------------
    // 删除操作
    //--------------------------------------------------------------------------
    /**
     * @brief deleteChar 删除光标后面一个字符;如有选区则删除选区内容
     */
    void deleteChar();

    /**
     * @brief deletePreviousChar 删除光标前面一个字符;如有选区删除选区
     */
    void deletePreviousChar();

    //--------------------------------------------------------------------------
    // 获取块、格式
    //--------------------------------------------------------------------------
    /**
     * @brief block 获取光标当前所在文本块(段落)
     * @return QTextBlock 当前块对象
     */
    QTextBlock block() const;

    /**
     * @brief blockNumber 获取当前块编号,从0开始
     * @return int 块索引
     */
    int blockNumber() const;

    /**
     * @brief blockFormat 获取当前光标处段落格式
     * @return QTextBlockFormat
     */
    QTextBlockFormat blockFormat() const;

    /**
     * @brief setBlockFormat 设置当前段落格式
     * @param format 段落格式对象
     */
    void setBlockFormat(const QTextBlockFormat &format);

    /**
     * @brief charFormat 获取光标位置字符格式
     * @return QTextCharFormat
     */
    QTextCharFormat charFormat() const;

    /**
     * @brief setCharFormat 设置字符格式;对选中文字生效,无选区则设置后续输入格式
     * @param format 字符格式
     */
    void setCharFormat(const QTextCharFormat &format);

    //--------------------------------------------------------------------------
    // 选区便捷接口
    //--------------------------------------------------------------------------
    /**
     * @brief selectAll 选中整个文档全部内容
     */
    void selectAll();

    //--------------------------------------------------------------------------
    // 重载赋值
    //--------------------------------------------------------------------------
    QTextCursor& operator=(const QTextCursor &other);
};

注意:

c++ 复制代码
//错误!cursor是副本,修改不会生效
QTextCursor cursor = ui->textEdit->textCursor();
cursor.insertText("abc");
//必须写回
ui->textEdit->setTextCursor(cursor);

快速上手

练习 1:在光标处插入文本

需求:

编辑框随便输入一些内容。点击按钮,在当前光标位置插入字符串 【插入测试】

c++ 复制代码
connect(ui->btnInsert,&QPushButton::clicked,this,[=](){
    QTextCursor cursor = ui->textEdit->textCursor();
    cursor.insertText("【插入测试】");
    ui->textEdit->setTextCursor(cursor); //写回控件
});

练习 2:移动光标到文档开头 / 末尾

两个按钮:

  • btnGoStart:光标跳到文档最开头
  • btnGoEnd:光标跳到文档末尾
c++ 复制代码
connect(ui->btnGoStart,&QPushButton::clicked,this,[=](){
    QTextCursor cursor = ui->textEdit->textCursor();
    cursor.movePosition(QTextCursor::Start);
    ui->textEdit->setTextCursor(cursor);
});

connect(ui->btnGoEnd,&QPushButton::clicked,this,[=](){
    QTextCursor cursor = ui->textEdit->textCursor();
    cursor.movePosition(QTextCursor::End);
    ui->textEdit->setTextCursor(cursor);
});
相关推荐
mqiqe2 小时前
线程调度与 Schedulers:Project Reactor 并发模型的核心引擎
java·开发语言·网络
xixiaoyunya3 小时前
JavaScript 异步编程全解析:从回调地狱到 async/await 的演进之路
开发语言·javascript·ecmascript
精英的英4 小时前
记一次 Qt5 Language Server 开发
开发语言·vscode·qt
烧酒同学4 小时前
【C++】记录size of std::vector的巧妙坑
开发语言·c++·图形渲染
周周哈哈哈4 小时前
线程创建、执行、退出、回收
java·开发语言
gb42152874 小时前
python中Web应用服务器
开发语言·前端·python
萧瑟余晖5 小时前
Java深入解析篇三十六之分布式系统详解
java·开发语言·分布式
ZJU_统一阿萨姆6 小时前
【推理优化进阶】调度器的数学内核:排队论、SLO 与在线决策
开发语言·人工智能·语言模型·系统架构·vllm
两个人的幸福online6 小时前
PHP 实现国密 SM3 踩坑记录:HMAC-SM3 签名对接 CNR 接口
开发语言·php