核心類職責
- 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();
}