QC++ / Qt 学习之路

案例:Markdown 编辑器与实时预览

左右分栏写 Markdown,语法高亮、实时预览与字数统计

实战第 45 / 48 章第六篇 · 案例实战

#这个案例做什么

写一个趁手的 Markdown 编辑器:左边写代码,右边实时出效果,中间的分隔条可以拖动调整比例;左侧编辑器带完整的 Markdown 语法高亮——标题、引用、列表、围栏代码块、粗体斜体、行内代码、链接各有颜色;支持打开保存、拖拽打开、修改标记、字数与行数的实时统计,还能把结果导出成 HTML 或 PDF 打印。它把 QPlainTextEdit、QSyntaxHighlighter、QTextDocument 的 Markdown 解析能力和 QSplitter 布局串成一条线,是理解 Qt 富文本体系最好的入口。

Markdown 编辑器 · QSplitter 文件 编辑 格式 视图 帮助 打开 保存 加粗 斜体 标题 预览 # 学习笔记 ## 第 3 章 控件 - 列表项:信号与槽 - 列表项:布局管理 **Qt 核心机制** > 引用:实践出真知 > 引用:多写多练 学习笔记 第 3 章 控件 信号与槽 布局管理 Qt 核心机制 引用:实践出真知 引用:多写多练 字数 1,238 · 行 42 · UTF-8 已保存 QSplitter 分隔条 QTextEdit 源码 QTextBrowser 预览
Markdown 编辑器界面结构——左侧编辑区 + 右侧预览区 + 底部统计栏

功能清单:

  • 左右分栏:QSplitter 水平布局,分隔条可拖动,比例自动保存;
  • 语法高亮:标题、引用、无序/有序列表、围栏代码块、粗体、斜体、删除线、行内代码、链接;
  • 实时预览:输入后延时 150 毫秒渲染,边输入边看结果,不卡手;
  • 滚动同步:拖动一侧滚动条,另一侧按比例跟随;
  • 文件操作:新建 / 打开 / 保存 / 另存为 / 导出 HTML / 打印或导出 PDF;
  • 统计栏:字符数、中文字数、单词数、行数、光标所在行列;
  • 窗口几何、最近文件路径用 QSettings 持久化,未保存修改时退出会拦截提示。

#用到的知识点

知识点出处
QSplitter 与布局管理第三篇第 7 章 布局管理
QPlainTextEdit 与 QTextDocument第三篇第 6 章 常用基础控件
QSyntaxHighlighter 自定义高亮第四篇第 4 章 自定义控件与 QSS
QTextDocument::setMarkdown 与 Markdown 方言第四篇第 5 章 绘图系统 QPainter(富文本文档)
QTextBrowser、QTextCursor、QTextBlock第三篇第 6 章 常用基础控件
QRegularExpression 正则匹配第三篇第 5 章 Qt 核心数据类型
QFileDialog、QMessageBox、QPrintDialog第四篇第 1 章 对话框与交互
QFile / QSaveFile / QTextStream第四篇第 6 章 文件与数据持久化
QSettings 界面状态持久化第四篇第 6 章 文件与数据持久化
QTimer 延时防抖与 QShortcut第三篇第 6 章 常用基础控件
信号槽与 lambda第三篇第 3 章 元对象系统与信号槽

#项目结构

Text
markdown-editor/
├── CMakeLists.txt
└── src/
    ├── main.cpp
    ├── highlighter.h
    ├── highlighter.cpp      # QSyntaxHighlighter 子类
    ├── editor.h
    ├── editor.cpp           # QPlainTextEdit 子类:行号栏 + Tab 缩进
    ├── mainwindow.h
    └── mainwindow.cpp       # 分栏、预览、文件、统计

Editor 只做两件事:显示行号栏和处理 Tab 键,它不知道 Markdown 的存在;Highlighter 只认文本块、不碰控件;MainWindow 负责把三者粘起来。这样分工之后,把编辑器换成表格编辑器、把预览换成网页视图都不需要改动另外两个文件。

CMake
cmake_minimum_required(VERSION 3.16)

project(MarkdownEditor LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_AUTOMOC ON)

find_package(Qt6 REQUIRED COMPONENTS Widgets PrintSupport)

qt_add_executable(MarkdownEditor
    src/main.cpp
    src/highlighter.cpp
    src/highlighter.h
    src/editor.cpp
    src/editor.h
    src/mainwindow.cpp
    src/mainwindow.h
)

target_link_libraries(MarkdownEditor PRIVATE
    Qt6::Widgets
    Qt6::PrintSupport
)

if(MSVC)
    target_compile_options(MarkdownEditor PRIVATE /utf-8)
endif()

#核心实现

#语法高亮器:块状态解决跨行结构

QSyntaxHighlighter 的工作方式是:文档每变化一个文本块,就对受影响的块调用 highlightBlock(),你在里面用正则匹配、调用 setFormat(起点, 长度, 格式) 上色。它天然适合单行规则,但 Markdown 的围栏代码块是跨行的——` ` 之后直到下一个围栏之间的所有行都是代码,而 highlightBlock` 每次只看一行。

解决办法是 previousBlockState() / setCurrentBlockState():自己约定两个整数状态(Normal = 0、InCode = 1),进入围栏时把当前块状态设为 InCode,下一块开头读到 previousBlockState() == InCode 就知道自己在代码里,直接整行上色,直到遇到结束围栏再设回 Normal。这是所有跨行语法高亮(多行注释、多行字符串、HTML 标签)的通用套路。

行内规则要在行级规则之后应用。因为 setFormat 是覆盖式的,后调用的会盖掉先调用的,如果先给整行加了引用色再画标题,标题色就会被冲掉——所以顺序必须是 代码围栏 → 标题 → 引用 → 列表 → 行内。

C++
// src/highlighter.h
#pragma once

#include <QSyntaxHighlighter>
#include <QRegularExpression>
#include <QTextCharFormat>

class Highlighter : public QSyntaxHighlighter
{
    Q_OBJECT
public:
    explicit Highlighter(QTextDocument *parent);

protected:
    void highlightBlock(const QString &text) override;

private:
    // 块状态常量,0 是 QSyntaxHighlighter 的默认状态
    enum BlockState { Normal = 0, InCode = 1 };

    void applyInline(const QString &text, const QRegularExpression &re,
                     const QTextCharFormat &fmt, int group = 0);
    static bool isFenceLine(const QString &text);

    QTextCharFormat m_heading;
    QTextCharFormat m_quote;
    QTextCharFormat m_list;
    QTextCharFormat m_code;
    QTextCharFormat m_inlineCode;
    QTextCharFormat m_bold;
    QTextCharFormat m_italic;
    QTextCharFormat m_strike;
    QTextCharFormat m_linkText;
    QTextCharFormat m_linkUrl;
    QTextCharFormat m_rule;

    QRegularExpression m_reFence;
    QRegularExpression m_reHeading;
    QRegularExpression m_reQuote;
    QRegularExpression m_reList;
    QRegularExpression m_reRule;
    QRegularExpression m_reInlineCode;
    QRegularExpression m_reBoldItalic;
    QRegularExpression m_reBold;
    QRegularExpression m_reItalic;
    QRegularExpression m_reStrike;
    QRegularExpression m_reLink;
};
C++
// src/highlighter.cpp
#include "highlighter.h"

Highlighter::Highlighter(QTextDocument *parent) : QSyntaxHighlighter(parent)
{
    // 格式只在这里构造一次;highlightBlock 每敲一个字符都会被调用,
    // 在里面反复构造 QTextCharFormat 是纯浪费
    m_heading.setForeground(QColor(61, 130, 220));
    m_heading.setFontWeight(QFont::Bold);

    m_quote.setForeground(QColor(120, 130, 145));
    m_quote.setFontItalic(true);

    m_list.setForeground(QColor(200, 120, 60));

    m_code.setForeground(QColor(190, 80, 90));
    m_code.setBackground(QColor(0, 0, 0, 18));

    m_inlineCode.setForeground(QColor(190, 80, 90));
    m_inlineCode.setBackground(QColor(0, 0, 0, 18));

    m_bold.setFontWeight(QFont::Bold);
    m_bold.setForeground(QColor(40, 44, 52));
    m_italic.setFontItalic(true);
    m_italic.setForeground(QColor(40, 44, 52));

    m_strike.setFontStrikeOut(true);
    m_strike.setForeground(QColor(130, 130, 135));

    m_linkText.setForeground(QColor(64, 140, 200));
    m_linkText.setFontUnderline(true);
    m_linkUrl.setForeground(QColor(110, 150, 170));
    m_linkUrl.setFontItalic(true);

    m_rule.setForeground(QColor(160, 160, 170));

    // 正则同样只编译一次;QRegularExpression 对象可复制、线程安全(只读)
    m_reFence      = QRegularExpression(QStringLiteral("^\\s*(```|~~~)"));
    m_reHeading    = QRegularExpression(QStringLiteral("^\\s*(#{1,6})\\s+.*$"));
    m_reQuote      = QRegularExpression(QStringLiteral("^\\s*>"));
    m_reList       = QRegularExpression(QStringLiteral("^\\s*(?:[-*+]|\\d+\\.)\\s+"));
    m_reRule       = QRegularExpression(QStringLiteral("^\\s*(?:\\*\\*\\*|---|___)\\s*$"));
    m_reInlineCode = QRegularExpression(QStringLiteral("`[^`\\n]+`"));
    m_reBoldItalic = QRegularExpression(QStringLiteral("\\*\\*\\*(?=\\S)(.+?)(?<=\\S)\\*\\*\\*"));
    m_reBold       = QRegularExpression(QStringLiteral("\\*\\*(?=\\S)(.+?)(?<=\\S)\\*\\*|__(?=\\S)(.+?)__"));
    m_reItalic     = QRegularExpression(QStringLiteral("(?<!\\*)\\*(?=\\S)([^*\\n]+?)(?<=\\S)\\*(?!\\*)"));
    m_reStrike     = QRegularExpression(QStringLiteral("~~(?=\\S)(.+?)(?<=\\S)~~"));
    m_reLink       = QRegularExpression(QStringLiteral("\\[([^\\]\\n]*)\\]\\(([^)\\n]*)\\)"));
}

bool Highlighter::isFenceLine(const QString &text)
{
    return text.trimmed().startsWith(QStringLiteral("```"))
        || text.trimmed().startsWith(QStringLiteral("~~~"));
}

void Highlighter::highlightBlock(const QString &text)
{
    // 1. 还在代码块里:整行上色,直到遇到结束围栏
    if (previousBlockState() == InCode) {
        setFormat(0, text.length(), m_code);
        setCurrentBlockState(isFenceLine(text) ? Normal : InCode);
        return;
    }

    // 2. 代码块内的内容不做行内解析,否则 `*` 会被当成强调符号
    if (isFenceLine(text)) {
        setFormat(0, text.length(), m_code);
        setCurrentBlockState(InCode);
        return;
    }

    setCurrentBlockState(Normal);

    // 3. 行级规则:顺序不能颠倒,后画的会盖住先画的
    if (m_reHeading.match(text).hasMatch()) {
        setFormat(0, text.length(), m_heading);
    } else if (m_reRule.match(text).hasMatch()) {
        setFormat(0, text.length(), m_rule);
    } else if (m_reQuote.match(text).hasMatch()) {
        setFormat(0, text.length(), m_quote);
    } else {
        const auto lm = m_reList.match(text);
        if (lm.hasMatch())
            setFormat(lm.capturedStart(), lm.capturedLength(), m_list);
    }

    // 4. 行内规则:代码优先(内容里可能有 * 和 _),链接次之,最后是强调
    applyInline(text, m_reInlineCode, m_inlineCode);
    applyInline(text, m_reLink, m_linkText, 1);
    applyInline(text, m_reLink, m_linkUrl, 2);
    applyInline(text, m_reBoldItalic, m_bold);      // 先三重后两重
    applyInline(text, m_reBold, m_bold);
    applyInline(text, m_reItalic, m_italic);
    applyInline(text, m_reStrike, m_strike);
}

void Highlighter::applyInline(const QString &text, const QRegularExpression &re,
                              const QTextCharFormat &fmt, int group)
{
    if (!re.isValid()) return;
    auto it = re.globalMatch(text);
    while (it.hasNext()) {
        const QRegularExpressionMatch m = it.next();
        setFormat(m.capturedStart(group), m.capturedLength(group), fmt);
    }
}

#编辑器:行号栏与 Tab 缩进

QPlainTextEdit 没有行号栏,但预留了 paint 事件之外的一个口子:在竖排布局里给它左侧留一个固定宽度的 QWidget(或用 viewportMargins 留出空间),在 paintEvent 里把行号画到那块区域。关键是计算每一行的顶部坐标——要靠 document()->documentLayout()->blockBoundingRect() 和 contentOffset() 换算,直接用行号乘以行高会在折行时全部错位。

Tab 键默认会把焦点移走,必须截获 Key_Tab 插入缩进;更实用的是支持"选中多行整体缩进/反缩进",这是写列表和代码块时的高频操作。

C++
// src/editor.h
#pragma once

#include <QPlainTextEdit>

class Editor : public QPlainTextEdit
{
    Q_OBJECT
public:
    explicit Editor(QWidget *parent = nullptr);

    void lineNumberAreaPaintEvent(QPaintEvent *event);
    int  lineNumberAreaWidth() const;

protected:
    void resizeEvent(QResizeEvent *event) override;
    void keyPressEvent(QKeyEvent *event) override;
    bool event(QEvent *event) override;   // 处理 Ctrl+滚轮缩放字号

private:
    void updateLineNumberArea(const QRect &rect, int dy);
    void indentSelection(bool reverse);

    QWidget *m_lineNumberArea = nullptr;
    QColor   m_lineBg   = QColor(245, 246, 248);
    QColor   m_lineFg   = QColor(150, 155, 165);
};
C++
// src/editor.cpp
#include "editor.h"

#include <QAbstractTextDocumentLayout>
#include <QFontMetrics>
#include <QKeyEvent>
#include <QPainter>
#include <QTextBlock>
#include <QWheelEvent>

namespace {
// 左侧行号区单独一个控件,靠信号驱动重绘,逻辑最清晰
class LineNumberArea : public QWidget
{
public:
    explicit LineNumberArea(Editor *editor) : QWidget(editor), m_editor(editor) {}
    QSize sizeHint() const override
    { return QSize(m_editor->lineNumberAreaWidth(), 0); }

protected:
    void paintEvent(QPaintEvent *event) override
    { m_editor->lineNumberAreaPaintEvent(event); }

private:
    Editor *m_editor;
};
}

Editor::Editor(QWidget *parent) : QPlainTextEdit(parent)
{
    m_lineNumberArea = new LineNumberArea(this);

    // 等宽字体是写代码的基本要求
    QFont f(QStringLiteral("Menlo"));
    f.setStyleHint(QFont::Monospace);
    f.setPointSize(13);
    setFont(f);
    document()->setDefaultFont(f);

    setLineWrapMode(QPlainTextEdit::NoWrap);      // Markdown 一般用软换行体验更好
    setTabStopDistance(4 * QFontMetrics(f).horizontalAdvance(QLatin1Char(' ')));

    auto *layout = document()->documentLayout();
    connect(this, &QPlainTextEdit::updateRequest,
            this, [this](const QRect &rect, int dy) { updateLineNumberArea(rect, dy); });
    connect(layout, &QAbstractTextDocumentLayout::documentSizeChanged,
            this, [this] { m_lineNumberArea->update(); });
}

int Editor::lineNumberAreaWidth() const
{
    const int digits = QString::number(qMax(1, blockCount())).length();
    return 12 + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits;
}

void Editor::updateLineNumberArea(const QRect &rect, int dy)
{
    if (dy)
        m_lineNumberArea->scroll(0, dy);
    else
        m_lineNumberArea->update(0, rect.y(), m_lineNumberArea->width(), rect.height());
}

void Editor::resizeEvent(QResizeEvent *event)
{
    QPlainTextEdit::resizeEvent(event);
    // 用 viewportMargins 在左侧腾出位置,比布局嵌套简单且不影响滚动
    const QRect cr = contentsRect();
    m_lineNumberArea->setGeometry(QRect(cr.left(), cr.top(),
                                        lineNumberAreaWidth(), cr.height()));
    setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}

void Editor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
    QPainter painter(m_lineNumberArea);
    painter.fillRect(event->rect(), m_lineBg);

    // contentOffset 处理水平滚动,blockBoundingRect 处理任意高度的内容(含折行)
    const QPointF offset = contentOffset();
    const qreal top = event->rect().top() + offset.y();
    const qreal bottom = event->rect().bottom() + offset.y();

    QTextBlock block = firstVisibleBlock();
    qreal y = blockBoundingGeometry(block).translated(offset).top();

    painter.setPen(m_lineFg);
    while (block.isValid() && y <= bottom) {
        const qreal height = blockBoundingRect(block).height();
        if (block.isVisible() && y + height >= top)
            painter.drawText(0, int(y), m_lineNumberArea->width() - 4,
                             int(height), Qt::AlignRight | Qt::AlignVCenter,
                             QString::number(blockNumber(block) + 1));
        y += height;
        block = block.next();
    }
}

void Editor::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Tab || event->key() == Qt::Key_Backtab) {
        indentSelection(event->key() == Qt::Key_Backtab);
        event->accept();
        return;
    }
    QPlainTextEdit::keyPressEvent(event);
}

void Editor::indentSelection(bool reverse)
{
    QTextCursor cursor = textCursor();
    const int selStart = cursor.selectionStart();
    const int selEnd   = cursor.selectionEnd();

    cursor.setPosition(selStart);
    const int firstBlock = cursor.blockNumber();
    cursor.setPosition(selEnd);
    const int lastBlock = cursor.blockNumber();

    cursor.beginEditBlock();                  // 一次撤销就能回退整批操作
    for (int b = firstBlock; b <= lastBlock; ++b) {
        QTextCursor line(document()->findBlockByNumber(b));
        if (!line.isValid()) continue;

        if (reverse) {
            line.movePosition(QTextCursor::StartOfBlock);
            line.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 4);
            if (line.selectedText() == QStringLiteral("    "))
                line.removeSelectedText();
        } else {
            line.movePosition(QTextCursor::StartOfBlock);
            line.insertText(QStringLiteral("    "));
        }
    }
    cursor.endEditBlock();

    // 恢复选中范围,缩进后不丢选区
    cursor = textCursor();
    cursor.setPosition(selStart + (reverse ? -4 : 4), QTextCursor::MoveAnchor);
    cursor.setPosition(selEnd + (reverse ? -4 : 4) * (lastBlock - firstBlock + 1),
                       QTextCursor::KeepAnchor);
    setTextCursor(cursor);
}

bool Editor::event(QEvent *event)
{
    if (event->type() == QEvent::Wheel) {
        auto *we = static_cast<QWheelEvent *>(event);
        if (we->modifiers() & Qt::ControlModifier) {
            QFont f = font();
            const int size = f.pointSize() + (we->angleDelta().y() > 0 ? 1 : -1);
            f.setPointSize(qBound(8, size, 32));
            setFont(f);
            document()->setDefaultFont(f);
            setTabStopDistance(4 * QFontMetrics(f).horizontalAdvance(QLatin1Char(' ')));
            return true;
        }
    }
    return QPlainTextEdit::event(event);
}

#实时预览与滚动同步

预览不需要自己写 Markdown 解析器——QTextDocument 从 Qt 5.14 起内置了 Markdown 支持,document()->setMarkdown(text) 一行就能得到排版好的文档,还能用 QTextDocument::MarkdownDialectGitHub 打开表格、删除线等 GitHub 扩展语法。

必须加防抖:textChanged 每个字符都会触发,一篇 5000 字的文章每敲一下就完整解析一次,输入会明显发涩。用一个 QTimer 配 setSingleShot(true),每次输入都调用 start(150),它会把计时重置,只有连续 150 毫秒没有输入才真正渲染。这是 GUI 里最常见的节流手段。

滚动同步按比例映射即可:两侧的滚动条取值范围不同,用 value / (maximum - minimum) 得到 0–1 的比例再换算过去。要防止 A 触发 B、B 又反过来触发 A 的回环,用一个标志位或直接比较比例是否已接近。

C++
// src/mainwindow.cpp(预览与同步部分)
void MainWindow::buildPreview()
{
    m_editor  = new Editor(this);
    m_preview = new QTextBrowser(this);
    m_preview->setOpenExternalLinks(true);          // 点链接用系统浏览器打开
    m_preview->document()->setDocumentMargin(12);

    // 预览区跟着编辑器用同一套字体,观感统一
    m_preview->setFont(QFontDatabase::systemFont(QFontDatabase::GeneralFont));

    m_splitter = new QSplitter(Qt::Horizontal, this);
    m_splitter->addWidget(m_editor);
    m_splitter->addWidget(m_preview);
    m_splitter->setStretchFactor(0, 1);
    m_splitter->setStretchFactor(1, 1);
    m_splitter->setSizes({ 500, 500 });
    setCentralWidget(m_splitter);

    new Highlighter(m_editor->document());

    // 防抖:150ms 内连续输入只渲染最后一次
    m_renderTimer = new QTimer(this);
    m_renderTimer->setSingleShot(true);
    connect(m_renderTimer, &QTimer::timeout, this, &MainWindow::renderPreview);
    connect(m_editor, &QPlainTextEdit::textChanged,
            this, [this] { m_renderTimer->start(150); });

    // 滚动同步:只在编辑器侧滚动时驱动预览,避免相互触发
    connect(m_editor->verticalScrollBar(), &QScrollBar::valueChanged,
            this, &MainWindow::syncPreviewScroll);
    connect(m_editor, &QPlainTextEdit::cursorPositionChanged,
            this, &MainWindow::updateStats);
}

void MainWindow::renderPreview()
{
    const QString text = m_editor->toPlainText();

    // 保存滚动比例,重设内容会把它清零
    QScrollBar *vs = m_preview->verticalScrollBar();
    const double ratio = vs->maximum() > 0
        ? double(vs->value()) / double(vs->maximum()) : 0.0;

    m_preview->document()->setMarkdown(text, QTextDocument::MarkdownDialectGitHub);

    if (vs->maximum() > 0)
        vs->setValue(int(ratio * vs->maximum()));

    m_dirty = true;
    updateTitle();
    updateStats();
}

void MainWindow::syncPreviewScroll(int value)
{
    QScrollBar *src = m_editor->verticalScrollBar();
    QScrollBar *dst = m_preview->verticalScrollBar();
    if (src->maximum() == 0 || dst->maximum() == 0) return;

    // 用"是否由用户拖动"来打断回环:比例差小于 1% 时直接忽略
    const double r = double(value) / double(src->maximum());
    const double cur = double(dst->value()) / double(dst->maximum());
    if (qAbs(r - cur) < 0.01) return;

    dst->setValue(int(r * dst->maximum()));
}

void MainWindow::updateStats()
{
    const QString text = m_editor->toPlainText();

    // 中英文混排要分开统计:CJK 按字数,拉丁按空格切词
    int cjk = 0;
    for (const QChar ch : text)
        if (ch.script() == QChar::Script_Han) ++cjk;

    const QStringList words =
        text.split(QRegularExpression(QStringLiteral("\\s+")), Qt::SkipEmptyParts);

    const QTextCursor c = m_editor->textCursor();
    m_stats->setText(QStringLiteral("字符 %1 中文字 %2 词 %3 行 %4 行列 %5:%6")
                         .arg(text.length())
                         .arg(cjk)
                         .arg(words.size())
                         .arg(m_editor->document()->blockCount())
                         .arg(c.blockNumber() + 1)
                         .arg(c.positionInBlock() + 1));
}

#文件读写、导出与退出拦截

文件 IO 有几条固定纪律:读文件直接按 UTF-8 解码(QTextStream::setEncoding);写文件用 QSaveFile 做原子替换;路径存在 m_filePath,为空表示"还没存过",保存时走另存为。标题上的 * 由 isWindowModified() 驱动,配合 Qt 的 [*] 占位符语法,一行 setWindowModified(m_dirty) 就能自动显示。

C++
// src/mainwindow.cpp(文件操作部分)
void MainWindow::openFile(const QString &path)
{
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::warning(this, QStringLiteral("打开失败"), file.errorString());
        return;
    }

    QTextStream in(&file);
    in.setEncoding(QStringConverter::Utf8);   // Qt 6 用 QStringConverter 取代 setCodec
    const QString text = in.readAll();

    m_editor->setPlainText(text);
    m_filePath = path;
    m_dirty = false;
    renderPreview();
    updateTitle();
    addRecentFile(path);
}

void MainWindow::saveFile(const QString &path)
{
    QSaveFile file(path);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, QStringLiteral("保存失败"), file.errorString());
        return;
    }

    QTextStream out(&file);
    out.setEncoding(QStringConverter::Utf8);
    // 统一换行:存成 \n,跨平台 diff 才不会满屏红
    out << m_editor->toPlainText().replace(QStringLiteral("\r\n"), QStringLiteral("\n"));

    if (!file.commit()) {
        QMessageBox::warning(this, QStringLiteral("保存失败"), file.errorString());
        return;
    }

    m_filePath = path;
    m_dirty = false;
    updateTitle();
    addRecentFile(path);
    statusBar()->showMessage(QStringLiteral("已保存 %1").arg(path), 3000);
}

void MainWindow::saveAs()
{
    const QString path = QFileDialog::getSaveFileName(
        this, QStringLiteral("另存为"), m_filePath,
        QStringLiteral("Markdown 文件 (*.md *.markdown);;文本文件 (*.txt);;所有文件 (*)"));
    if (path.isEmpty()) return;
    saveFile(path);
}

void MainWindow::exportHtml()
{
    const QString path = QFileDialog::getSaveFileName(
        this, QStringLiteral("导出 HTML"), QString(), QStringLiteral("HTML (*.html)"));
    if (path.isEmpty()) return;

    // 直接把预览区的 QTextDocument 转成 HTML,样式与所见一致
    QSaveFile file(path);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return;

    QString html = m_preview->document()->toHtml();
    html.replace(QStringLiteral("<head>"),
                 QStringLiteral("<head><meta charset=\"utf-8\">"));
    file.write(html.toUtf8());
    file.commit();
    statusBar()->showMessage(QStringLiteral("已导出 %1").arg(path), 3000);
}

void MainWindow::print()
{
    QPrinter printer(QPrinter::HighResolution);
    QPrintDialog dlg(&printer, this);
    if (dlg.exec() != QDialog::Accepted) return;
    // 打印需要 PrintSupport 模块,文档直接交给 QTextDocument::print
    m_preview->document()->print(&printer);
}

bool MainWindow::maybeSave()
{
    if (!m_dirty) return true;
    const auto ret = QMessageBox::question(
        this, QStringLiteral("未保存的修改"),
        QStringLiteral("当前文档有未保存的修改,是否保存?"),
        QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);

    if (ret == QMessageBox::Save)   { saveAs(); return !m_dirty; }
    if (ret == QMessageBox::Cancel) { return false; }
    return true;
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (!maybeSave()) { event->ignore(); return; }

    QSettings settings;
    settings.setValue(QStringLiteral("geometry"), saveGeometry());
    settings.setValue(QStringLiteral("splitter"), m_splitter->saveState());
    event->accept();
}
C++
// src/main.cpp
#include <QApplication>
#include <QCoreApplication>

#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QCoreApplication::setOrganizationName(QStringLiteral("QtTutorial"));
    QCoreApplication::setApplicationName(QStringLiteral("MarkdownEditor"));

    MainWindow w;
    w.show();

    // 双击 .md 文件打开时,系统会把路径作为命令行参数传进来
    if (argc > 1)
        w.openFile(QString::fromLocal8Bit(argv[1]));

    return app.exec();
}

#关键细节与踩坑

1. 输入卡顿,敲一个字等半秒。 textChanged 每字符触发一次,直接渲染整篇 Markdown 会让长文档输入明显发涩。用 QTimer 单次触发做 150 毫秒防抖即可;文档超过两万字时可以进一步改成"输入时只渲染当前段落,停手后才全量渲染"。另外 QTextDocument::setMarkdown 内部会重建整个文档结构,别在定时器回调之外的地方调用它。

2. 代码块的星号被当成强调,或者引用行里的标题不上色。 两个方向都要处理:跨行结构靠 previousBlockState() 传递状态,代码块内直接 return 跳过所有行内规则;行内规则必须在行级规则之后应用,因为 setFormat 是覆盖式的。顺序搞反的表现是"标题颜色正常但代码块里的 * 全变成斜体"。

3. 行号对不上,折行后全乱。 行号不能靠 行号 × 行高 算,因为每个文本块高度都可能不同(图片、大字、折行)。正确姿势是遍历 firstVisibleBlock() 开始的 QTextBlock,累加 blockBoundingRect(block).height(),并加上 contentOffset() 补偿水平滚动与文档边距。

4. 滚动同步陷入死循环。 两侧 valueChanged 互相触发,表现为滚动条抖动。用一个"同步中"的标志位包住赋值动作,或者像本案例那样比较比例差异小于 1% 就直接忽略。更彻底的做法是只在编辑器侧连接信号(本案例的做法),单向驱动不会有环。

5. 中文乱码、换行符对不上。 Qt 6 里 QTextStream::setCodec("UTF-8") 已经移除,改用 setEncoding(QStringConverter::Utf8)。跨平台协作还要统一换行:Windows 存出来是 \r\n,与 Git 仓库里的 \n 混在一起会让 diff 满屏红,保存前做一次替换最省事。

6. 打印/导出 PDF 得到空白页。 QTextDocument::print() 依赖 QtPrintSupport 模块,CMake 里必须 find_package(Qt6 REQUIRED COMPONENTS PrintSupport) 并链接,缺了会在链接期报一堆找不到符号。另外 QPrinter 要在 QPrintDialog 之前构造并把分辨率设成 HighResolution,否则文字会糊。

#还能怎么扩展

  • 所见即所得的标题折叠:用 QTextBlockUserData 记录折叠状态,配合 QTextBlock::setVisible(false) 实现段落折叠,这是 Qt Creator 折叠功能的实现方式。
  • 粘贴图片:重写 insertFromMimeData,检测剪贴板里的 QImage,存成相对路径的附件文件后插入 ![alt](path),配合文档目录管理附件。
  • 大纲导航:用正则扫出所有 # 标题,生成一个 QTreeWidget 侧栏,点击跳转用 setTextCursor + centerCursor()。
  • 自定义 Markdown 解析器:本案例直接用了内置解析;想练手可以按块遍历 QTextDocument,自己处理标题/列表/引用/代码/表格,用 QTextCursor::insertBlock 与 QTextBlockFormat 逐块构建,理解真实的解析流程。
  • 多标签页:用 QTabWidget 承载多个 Editor,每个页签一个 Highlighter,关闭前走 maybeSave();再加上 QFileSystemWatcher 监听外部修改并提示重新载入。

#小结

  • QSyntaxHighlighter 只对受影响的文本块工作,跨行结构必须用 previousBlockState / setCurrentBlockState 传递状态。
  • 行级规则先画、行内规则后画,setFormat 是覆盖式的;代码块内要跳过行内解析;正则与 QTextCharFormat 在构造函数里准备一次,highlightBlock 里只做匹配和着色。
  • 实时预览一定要防抖:单次触发的 QTimer 是最简单有效的节流手段;滚动同步要防回环。
  • 行号栏靠 viewportMargins + 单独控件绘制,坐标要用 blockBoundingRect 累加而不是行号乘行高。
  • 文件读写统一 UTF-8、QSaveFile 原子写、\r\n 归一化;PrintSupport 模块要显式引入。

#练习

  1. 增加"大纲视图":在 QSplitter 最左侧加一个 QListWidget,解析出所有 #~###### 标题(记录 blockNumber),点击时构造 QTextCursor 定位到该块并 centerCursor(),输入时定时刷新列表。
  2. 实现 Ctrl+/ 注释切换:拿当前行文本判断,若以 <!-- 开头则去掉注释标记,否则用 <!-- text --> 包裹,用 QTextCursor 选中整行再 insertText。
  3. 加一个"导出 PDF"动作:构造 QPrinter 并设置 setOutputFormat(QPrinter::PdfFormat)、setOutputFileName(),直接调用 m_preview->document()->print(&printer),不需要弹出打印对话框。
  4. 支持拖拽打开 .md 文件:在主窗口 setAcceptDrops(true),重写 dragEnterEvent 检查 mimeData()->hasUrls() 与后缀为 md,dropEvent 里取 toLocalFile() 调用 openFile();注意先判断 maybeSave() 避免覆盖未保存内容。
我的学习笔记笔记总览
笔记保存在本机浏览器(localStorage),换设备或清理缓存会丢失;重要内容请点「导出全部笔记」存成 .md 文件。