WebEngine Markdown Editor Example▲
Markdown Editor demonstrates how to use QWebChannel and JavaScript libraries to provide a rich text preview tool for a custom markup language.
Markdown is a lightweight markup language with a plain text formatting syntax. Some services, such as github, acknowledge the format, and render the content as rich text when viewed in a browser.
The Markdown Editor main window is split into an editor and a preview area. The editor supports the Markdown syntax and is implemented by using QPlainTextEdit. The document is rendered as rich text in the preview area, which is implemented by using QWebEngineView. To render the text, the Markdown text is converted to HTML format with the help of a JavaScript library inside the web engine. The preview is updated from the editor through QWebChannel.
Running the Example▲
To run the example from Qt Creator, open the Welcome mode and select the example from Examples. For more information, visit Building and Running an Example.
Exposing Document Text▲
Because we expose the current Markdown text to be rendered to the web engine through QWebChannel, we need to somehow make the current text available through the Qt metatype system. This is done by using a dedicated Document class that exposes the document text as a Q_PROPERTY:
class
Document : public
QObject
{
Q_OBJECT
Q_PROPERTY(QString text MEMBER m_text NOTIFY textChanged FINAL)
public
:
explicit
Document(QObject *
parent =
nullptr
) : QObject(parent) {}
void
setText(const
QString &
amp;text);
signals
:
void
textChanged(const
QString &
amp;text);
private
:
QString m_text;
}
;
The Document class wraps a QString to be set on the C++ side with the setText() method and exposes it at runtime as a text property with a textChanged signal.
We define the setText method as follows:
void
Document::
setText(const
QString &
amp;text)
{
if
(text ==
m_text)
return
;
m_text =
text;
emit textChanged(m_text);
}
Previewing Text▲
We implement our own PreviewPage class that publicly inherits from QWebEnginePage:
class
PreviewPage : public
QWebEnginePage
{
Q_OBJECT
public
:
using
QWebEnginePage::
QWebEnginePage;
protected
:
bool
acceptNavigationRequest(const
QUrl &
amp;url, NavigationType type, bool
isMainFrame) override
;
}
;
We reimplement the virtual acceptNavigationRequest method to stop the page from navigating away from the current document. Instead, we redirect external links to the system browser:
bool
PreviewPage::
acceptNavigationRequest(const
QUrl &
amp;url,
QWebEnginePage::
NavigationType /*type*/
,
bool
/*isMainFrame*/
)
{
// Only allow qrc:/index.html.
if
(url.scheme() ==
QString("qrc"
))
return
true
;
QDesktopServices::
openUrl(url);
return
false
;
}
Creating the Main Window▲
The MainWindow class inherits the QMainWindow class:
class
MainWindow : public
QMainWindow
{
Q_OBJECT
public
:
explicit
MainWindow(QWidget *
parent =
nullptr
);
~
MainWindow();
void
openFile(const
QString &
amp;path);
protected
:
void
closeEvent(QCloseEvent *
e) override
;
private
slots:
void
onFileNew();
void
onFileOpen();
void
onFileSave();
void
onFileSaveAs();
private
:
bool
isModified() const
;
Ui::
MainWindow *
ui;
QString m_filePath;
Document m_content;
}
;
The class declares private slots that match the actions in the menu, as well as the isModified() helper method.
The actual layout of the main window is specified in a .ui file. The widgets and actions are available at runtime in the ui member variable.
m_filePath holds the file path to the currently loaded document. m_content is an instance of the Document class.
The actual setup of the different objects is done in the MainWindow constructor:
MainWindow::
MainWindow(QWidget *
parent) :
QMainWindow(parent),
ui(new
Ui::
MainWindow)
{
ui-&
gt;setupUi(this
);
ui-&
gt;editor-&
gt;setFont(QFontDatabase::
systemFont(QFontDatabase::
FixedFont));
ui-&
gt;preview-&
gt;setContextMenuPolicy(Qt::
NoContextMenu);
The constructor first calls setupUi to construct the widgets and menu actions according to the UI file. The text editor font is set to one with a fixed character width, and the QWebEngineView widget is told not to show a context menu.
PreviewPage *
page =
new
PreviewPage(this
);
ui-&
gt;preview-&
gt;setPage(page);
Here the constructor makes sure our custom PreviewPage is used by the QWebEngineView instance in ui->preview.
connect(ui-&
gt;editor, &
amp;QPlainTextEdit::
textChanged,
[this
]() {
m_content.setText(ui-&
gt;editor-&
gt;toPlainText()); }
);
QWebChannel *
channel =
new
QWebChannel(this
);
channel-&
gt;registerObject(QStringLiteral("content"
), &
amp;m_content);
page-&
gt;setWebChannel(channel);
Here the textChanged signal of the editor is connected to a lambda that updates the text in m_content. This object is then exposed to the JS side by QWebChannel under the name content.
ui-&
gt;preview-&
gt;setUrl(QUrl("qrc:/index.html"
));
Now we can actually load the index.html file from the resources. For more information about the file, see Creating an Index File.
connect(ui-&
gt;actionNew, &
amp;QAction::
triggered, this
, &
amp;MainWindow::
onFileNew);
connect(ui-&
gt;actionOpen, &
amp;QAction::
triggered, this
, &
amp;MainWindow::
onFileOpen);
connect(ui-&
gt;actionSave, &
amp;QAction::
triggered, this
, &
amp;MainWindow::
onFileSave);
connect(ui-&
gt;actionSaveAs, &
amp;QAction::
triggered, this
, &
amp;MainWindow::
onFileSaveAs);
connect(ui-&
gt;actionExit, &
amp;QAction::
triggered, this
, &
amp;QWidget::
close);
connect(ui-&
gt;editor-&
gt;document(), &
amp;QTextDocument::
modificationChanged,
ui-&
gt;actionSave, &
amp;QAction::
setEnabled);
The menu items are connected to the corresponding member slots. The Save item is activated or deactivated depending on whether the user has edited the content.
QFile defaultTextFile(":/default.md"
);
defaultTextFile.open(QIODevice::
ReadOnly);
ui-&
gt;editor-&
gt;setPlainText(defaultTextFile.readAll());
}
Finally, we load a default document default.md from the resources.
Creating an Index File▲
&
lt;!
doctype html&
gt;
&
lt;html lang=
"en"
&
gt;
&
lt;meta charset=
"utf-8"
&
gt;
&
lt;head&
gt;
&
lt;link rel=
"stylesheet"
type=
"text/css"
href=
"3rdparty/markdown.css"
&
gt;
&
lt;script src=
"3rdparty/marked.js"
&
gt;&
lt;/
script&
gt;
&
lt;script src=
"qrc:/qtwebchannel/qwebchannel.js"
&
gt;&
lt;/
script&
gt;
&
lt;/
head&
gt;
&
lt;body&
gt;
&
lt;div id=
"placeholder"
&
gt;&
lt;/
div&
gt;
&
lt;script&
gt;
'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);
}
);
&
lt;/
script&
gt;
&
lt;/
body&
gt;
&
lt;/
html&
gt;
In the index.html, we load a custom stylesheet and two JavaScript libraries. markdown.css is a markdown-friendly stylesheet created by Kevin Burke. marked.js is a markdown parser and compiler designed for speed written by Christopher Jeffre