首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Qt 富文本編輯器核心代碼結構解析:QTextDocument、Frame、Block、Cursor 協作機制

     編輯:程式設計疑難解答

核心類職責

  • QTextDocument:文檔模型,持有所有內容(字符、格式、圖片、表格),提供 rootFrame()、find()、undo/redo。
  • QTextFrame:框架節點,可巢狀(如表格、列表、文檔根框架),對應 HTML <div> 等塊級容器。
  • QTextBlock:段落/塊,文檔的基本編輯單位,包含格式 (QTextBlockFormat) 和文本行。
  • QTextCursor:編輯游標,提供插入、刪除、選中、格式化 API,維持位置穩定性。

工具欄動作綁定

// 字體加粗
QAction *boldAct = new QAction(tr("加粗"), this);
boldAct->setCheckable(true);
connect(boldAct, &QAction::toggled, [this](bool on) {
    QTextCharFormat fmt;
    fmt.setFontWeight(on ? QFont::Bold : QFont::Normal);
    ui->textEdit->textCursor().mergeCharFormat(fmt);
});

查找功能

void MainWindow::textFind() {
    QDialog *dlg = new QDialog(this);
    QLineEdit *edit = new QLineEdit(dlg);
    QPushButton *btn = new QPushButton("查找下一個", dlg);
    connect(btn, &QPushButton::clicked, [=] {
        bool found = ui->textEdit->find(edit->text(), QTextDocument::FindBackward);
        if (!found) QMessageBox::information(this, "提示", "未找到");
    });
    // layout...
    dlg->exec();
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved