基於QWebEngineView與QWebChannel實現的Markdown編輯器。
Markdown編輯器演示瞭如何使用QWebChannel和JavaScript庫爲自定義標記語言提供富文本預覽工具。css
Markdown是一種輕量級的標記語言,具備純文本格式語法。能夠在瀏覽器中查看時將內容呈現爲富文本格式。html
Markdown編輯器主窗口分爲編輯區域和預覽區域。web
該編輯器區域使用QPlainTextEdit實現。瀏覽器
預覽區域使用QWebEngineView實現的。爲了呈現文本,藉助Web引擎內部的JavaScript庫,將Markdown文本轉換爲HTML格式。預覽是經過QWebChannel發送編輯區域的文本內容到QWebEngineView渲染(支持邊編輯邊渲染更新)。markdown
QFile defaultTextFile(":/default.md"); defaultTextFile.open(QIODevice::ReadOnly); ui->editor->setPlainText(defaultTextFile.readAll());
connect(ui->editor, &QPlainTextEdit::textChanged, [this]() { m_content.setText(ui->editor->toPlainText()); }); QWebChannel *channel = new QWebChannel(this); channel->registerObject(QStringLiteral("content"), &m_content); page->setWebChannel(channel);
ui->preview->setUrl(QUrl("qrc:/index.html"));
<!doctype html> <html lang="en"> <meta charset="utf-8"> <head> <link rel="stylesheet" type="text/css" href="3rdparty/markdown.css"> <script src="3rdparty/marked.js"></script> <script src="qrc:/qtwebchannel/qwebchannel.js"></script> </head> <body> <div id="placeholder"></div> <script> 'use strict'; var placeholder = document.getElementById('placeholder'); var updateText = function(text) { placeholder.innerHTML = marked(text); } new QWebChannel(qt.webChannelTransport, function(channel) { var content = channel.objects.content; updateText(content.text); content.textChanged.connect(updateText); } ); </script> </body> </html>
C:\Qt\{你的Qt版本}\Examples\{你的Qt版本}\webenginewidgets\markdowneditor
https://doc.qt.io/qt-5/qtwebengine-webenginewidgets-markdowneditor-example.html