Include qmarkdowntextedit.pri
to your project like this include (qmarkdowntextedit/qmarkdowntextedit.pri)
add a normal QPlainTextEdit to your UI and promote it to QMarkdownTextEdit (base class QPlainTextEdit)
CMake
Include CMakeLists.txt
to your project like this add_subdirectory(qmarkdowntextedit)
add a normal QPlainTextEdit to your UI and promote it to QMarkdownTextEdit (base class QPlainTextEdit)
Assistant
This is an excellent upgrade! Using a dedicated Markdown editor library like qmarkdowntextedit will significantly enhance the editing experience by adding syntax highlighting directly in the source code pane, making it much easier to write Markdown.
Here's how to integrate it.
Step 9: Integrate qmarkdowntextedit Library
First, we need to get the library into our project and tell CMake how to use it.
Click the green "Code" button, then "Download ZIP".
Extract the ZIP file.
Create a new folder named libs in the root directory of your Markpad project (the same directory where your main CMakeLists.txt is).
Move the extracted qmarkdowntextedit folder (the one containing src/, CMakeLists.txt, qmarkdowntextedit.pri, etc.) into the libs folder.
Your project structure should now look something like this:
code
Markpad/
├── CMakeLists.txt <-- Your main CMake file
├── libs/
│ └── qmarkdowntextedit/ <-- The downloaded library folder
│ ├── src/
│ ├── CMakeLists.txt
│ ├── qmarkdowntextedit.pri
│ └── ...
├── src/
│ ├── main.cpp
│ ├── mainwindow.cpp
│ ├── mainwindow.h
│ └── mainwindow.ui <-- (We are not using this, but it's generated)
└── ...
2. Configure CMake:
Open your main CMakeLists.txt file (in the root of your Markpad project).
Add the following line near the top, before you define your Markpad executable:
cmake
# Add the external library QMarkdownTextEdit
add_subdirectory(libs/qmarkdowntextedit)
Now, find where you link libraries in your (or wherever your is). You need to link against the library. Modify your command to include :
User
Usage guide says
Using the editor
QMake
code
Include qmarkdowntextedit.pri to your project like this include (qmarkdowntextedit/qmarkdowntextedit.pri)
add a normal QPlainTextEdit to your UI and promote it to QMarkdownTextEdit (base class QPlainTextEdit)
CMake
code
Include CMakeLists.txt to your project like this add_subdirectory(qmarkdowntextedit)
add a normal QPlainTextEdit to your UI and promote it to QMarkdownTextEdit (base class QPlainTextEdit)
Assistant
That's a very good observation! It highlights a common point of confusion when using Qt libraries that extend existing widgets, especially when the tutorial avoids using Qt Designer's .ui files.
You are absolutely right, the usage guide for qmarkdowntextedit suggests promoting a QPlainTextEdit to QMarkdownTextEdit when using a UI file (.ui).
Let me clarify why my current approach is correct and why the guide mentions "promotion":
Inheritance: The QMarkdownTextEdit class from the library inherits from QPlainTextEdit. This means a QMarkdownTextEditis aQPlainTextEdit and has all its capabilities, plus its own enhancements (syntax highlighting, etc.).
Qt Designer & UI Files: When you use Qt Designer to visually design your application's UI, you drag standard widgets (like QPlainTextEdit) onto your form. If you want to use a custom widget that extends a standard one (like QMarkdownTextEdit extends QPlainTextEdit), you use the "Promote to..." feature. This tells Qt Designer: "When you generate C++ code from this .ui file, replace instances of QPlainTextEdit with QMarkdownTextEdit."
Our Approach (Manual C++ UI): In this tutorial, we've intentionally avoided using Qt Designer and .ui files to focus on building the UI directly in C++ code.
In our setupEditor() function, we have this line:
cpp
sourceEditor = new QMarkdownTextEdit(this);
This is the C++ equivalent of what "promotion" achieves with a .ui file. Instead of telling Qt Designer to substitute a widget, we are directly creating an instance of the specialized widget (QMarkdownTextEdit).
Therefore, your current code is correct and achieves the intended result without needing to change it based on that specific part of the guide. You are directly instantiating the QMarkdownTextEdit which gives you all its features, including the syntax highlighting and other improvements mentioned.
Think of it this way:
Promotion (with .ui file): You visually place a QPlainTextEdit and tell the system "actually, make this a QMarkdownTextEdit."
Manual C++ Creation (our way): You directly say, "I want a QMarkdownTextEdit."
Both methods result in having a QMarkdownTextEdit object in your application. Since we're building purely in C++, direct instantiation is the most straightforward way.
# Example in src/CMakeLists.txt (or your main CMakeLists.txt if src/ is not a subdir)
# ... other settings ...
add_executable(Markpad
main.cpp
mainwindow.cpp
mainwindow.h
# ... other source files ...
)
# Link against Qt modules AND the qmarkdowntextedit library
target_link_libraries(Markpad PRIVATE
Qt6::Widgets
Qt6::Gui
Qt6::Core
qmarkdowntextedit # Link against the library target
)
(Note: The exact target name qmarkdowntextedit is usually specified in the library's own CMakeLists.txt.)
3. Rebuild the Project:
Crucially, close Qt Creator.
Go to your build directory (e.g., build-Markpad-Desktop_...).
Delete the contents of the build directory. This ensures CMake picks up the new CMake configuration correctly.
Re-open your CMakeLists.txt file in Qt Creator or run CMake from the command line.
Build the project again.
Step 10: Update Your Code to Use QMarkdownTextEdit
Now that the library is linked, we need to tell our application to use QMarkdownTextEdit instead of QPlainTextEdit.
mainwindow.h Changes:
Remove the include for QPlainTextEdit.
Add the include for QMarkdownTextEdit (the path might vary slightly depending on how the library installs its headers, but usually it's just <QMarkdownTextEdit>).
Change the type of sourceEditor.
cpp
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
// #include <QPlainTextEdit> // Remove this line
#include <QMarkdownTextEdit> // Add this line for the new editor
#include <QTextBrowser>
#include <QFileSystemModel>
#include <QTreeView>
#include <QMenu>
#include <QAction>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void openFile();
void saveFile();
void openFolder();
void openFileFromTree(const QModelIndex &index);
void updatePreview();
private:
void createMenus();
void createSidebar();
void setupEditor(); // This function will be updated to create QMarkdownTextEdit
Ui::MainWindow *ui;
// Changed: Use QMarkdownTextEdit for the source editor
QMarkdownTextEdit *sourceEditor;
QTextBrowser *previewer;
QMenu *fileMenu;
QAction *openAct;
QAction *openFolderAct;
QAction *saveAct;
QAction *exitAct;
QFileSystemModel *fileSystemModel;
QTreeView *fileTreeView;
QString currentFilePath;
};
#endif // MAINWINDOW_H
mainwindow.cpp Changes:
Update Include Path: Make sure the include path for QMarkdownTextEdit is correct. If <QMarkdownTextEdit> doesn't work after building, you might need to use a relative path like "qmarkdowntextedit/src/qmarkdowntextedit.h", but the <> style is preferred if CMake is set up correctly.
Modify setupEditor(): Change the instantiation of the source editor.
Enable Line Numbers:QMarkdownTextEdit has a specific function for this.
cpp
#include "mainwindow.h"
#include "./ui_mainwindow.h"
// Include necessary Qt modules
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QKeySequence>
#include <QSplitter>
#include <QHeaderView>
#include <QDir>
#include <QFont>
// Add this include for QMarkdownTextEdit
// Adjust the path if needed based on your CMake setup and library location.
// The most common way after add_subdirectory is:
#include <QMarkdownTextEdit>
// If that fails, try: #include "qmarkdowntextedit/src/qmarkdowntextedit.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
// ui->setupUi(this); // Keep this commented out for manual UI setup
// 1. Setup the editor/previewer layout
setupEditor();
// 2. Create Menus and Sidebar
createMenus();
createSidebar();
// 3. Connect the editor to the previewer
// When the source editor's text changes, update the preview.
// QMarkdownTextEdit inherits textChanged from QPlainTextEdit.
connect(sourceEditor, &QMarkdownTextEdit::textChanged, this, &MainWindow::updatePreview);
resize(1200, 700); // Make the window wider to accommodate the sidebar and split view
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::setupEditor()
{
// 1. Create the splitter (Horizontal layout for editor and preview)
QSplitter *splitter = new QSplitter(Qt::Horizontal, this);
// 2. Create the source editor
// NOW INSTANTIATE QMarkdownTextEdit INSTEAD OF QPlainTextEdit
sourceEditor = new QMarkdownTextEdit(this);
// Enable Markdown highlighting and other features provided by the library
// The library usually enables basic markdown highlighting by default.
// We can enable line numbers:
sourceEditor->setLineNumberShow(true);
// Set a monospace font for a better editing experience
QFont font("Monospace");
font.setStyleHint(QFont::Monospace);
sourceEditor->setFont(font);
// Optional: Set some initial markdown text if you like
// sourceEditor->setPlainText("# Welcome to Markpad\n\n* Item 1\n* Item 2\n\n`code`");
// 3. Create the previewer (Right side)
previewer = new QTextBrowser(this);
// 4. Add both widgets to the splitter
splitter->addWidget(sourceEditor);
splitter->addWidget(previewer);
// 5. Set the splitter as the central widget of the main window
setCentralWidget(splitter);
}
void MainWindow::updatePreview()
{
// Get the raw text from the source editor
QString markdownText = sourceEditor->toPlainText();
// Set the text to the previewer, telling it to render as Markdown
previewer->setMarkdown(markdownText);
}
// --- Menu and Sidebar functions remain largely the same ---
void MainWindow::createMenus()
{
fileMenu = menuBar()->addMenu(tr("&File"));
openAct = new QAction(tr("&Open File..."), this);
openAct->setShortcuts(QKeySequence::Open);
fileMenu->addAction(openAct);
connect(openAct, &QAction::triggered, this, &MainWindow::openFile);
openFolderAct = new QAction(tr("Open &Folder..."), this);
fileMenu->addAction(openFolderAct);
connect(openFolderAct, &QAction::triggered, this, &MainWindow::openFolder);
fileMenu->addSeparator();
saveAct = new QAction(tr("&Save"), this);
saveAct->setShortcuts(QKeySequence::Save);
fileMenu->addAction(saveAct);
connect(saveAct, &QAction::triggered, this, &MainWindow::saveFile);
fileMenu->addSeparator();
exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcuts(QKeySequence::Quit);
fileMenu->addAction(exitAct);
connect(exitAct, &QAction::triggered, this, &QWidget::close);
}
void MainWindow::createSidebar()
{
QDockWidget *dock = new QDockWidget(tr("File Explorer"), this);
dock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
addDockWidget(Qt::LeftDockWidgetArea, dock);
fileSystemModel = new QFileSystemModel(this);
// Set an initial root path for the model. This will be the starting point of the explorer.
// QDir::currentPath() is often a good default.
fileSystemModel->setRootPath(QDir::currentPath());
fileTreeView = new QTreeView(dock);
fileTreeView->setModel(fileSystemModel);
// Hide unnecessary columns (Size, Type, Date Modified) for a cleaner look
fileTreeView->header()->hideSection(1); // Size
fileTreeView->header()->hideSection(2); // Type
fileTreeView->header()->hideSection(3); // Date Modified
// Make the first column (Name) stretch to fill available space
fileTreeView->header()->setSectionResizeMode(0, QHeaderView::Stretch);
// Set the initial root index of the view to match the model's root path
fileTreeView->setRootIndex(fileSystemModel->index(QDir::currentPath()));
dock->setWidget(fileTreeView);
// Connect clicking an item in the tree view to our slot
connect(fileTreeView, &QTreeView::clicked, this, &MainWindow::openFileFromTree);
}
// --- File Open/Save functions (largely unchanged, but use the new sourceEditor) ---
void MainWindow::openFile()
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Open Markdown File"), "", tr("Markdown Files (*.md);;Text Files (*.txt);;All Files (*)"));
if (fileName.isEmpty())
return;
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QMessageBox::warning(this, tr("Error"), tr("Cannot read file %1:\n%2.").arg(fileName, file.errorString()));
return;
}
currentFilePath = fileName;
setWindowTitle(tr("%1 - Markpad").arg(fileName));
QTextStream in(&file);
QString content = in.readAll();
// Load the raw content into the source editor
sourceEditor->setPlainText(content); // setPlainText works for QMarkdownTextEdit
file.close();
// The textChanged signal will automatically trigger updatePreview
}
void MainWindow::saveFile()
{
QString fileName;
// If no file is currently open, prompt the user to choose a save location
if (currentFilePath.isEmpty()) {
fileName = QFileDialog::getSaveFileName(this, tr("Save Markdown File"), "", tr("Markdown Files (*.md);;Text Files (*.txt)"));
if (fileName.isEmpty()) // User cancelled
return;
currentFilePath = fileName;
} else {
fileName = currentFilePath;
}
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::warning(this, tr("Error"), tr("Cannot write file %1:\n%2.").arg(fileName, file.errorString()));
return;
}
setWindowTitle(tr("%1 - Markpad").arg(fileName));
QTextStream out(&file);
// Save exactly what's in the source editor's plain text content
out << sourceEditor->toPlainText(); // toPlainText works for QMarkdownTextEdit
file.close();
}
void MainWindow::openFileFromTree(const QModelIndex &index)
{
// If the clicked item is a directory, expand it and do nothing else.
if (fileSystemModel->isDir(index)) {
fileTreeView->expand(index);
return;
}
// Get the full path of the selected file
QString fileName = fileSystemModel->filePath(index);
// You might want to add a check here to only open .md or .txt files
// For now, we'll try to open any file and let it display raw text if it's not Markdown.
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QMessageBox::warning(this, tr("Error"), tr("Cannot read file %1:\n%2.").arg(fileName, file.errorString()));
return;
}
currentFilePath = fileName;
setWindowTitle(tr("%1 - Markpad").arg(fileName));
QTextStream in(&file);
QString content = in.readAll();
// Load the raw content into the source editor
sourceEditor->setPlainText(content);
file.close();
// The textChanged signal will automatically trigger updatePreview
}
void MainWindow::openFolder()
{
// Open the system's dialog to select an existing directory
QString dirPath = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
QDir::homePath(), // Start browsing from the user's home directory
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
// If the user cancelled the dialog, dirPath will be empty
if (dirPath.isEmpty())
return;
// Update the QFileSystemModel to use the selected directory as its root
fileSystemModel->setRootPath(dirPath);
// Update the QTreeView to display contents starting from the selected directory
fileTreeView->setRootIndex(fileSystemModel->index(dirPath));
}
What this integration does:
Syntax Highlighting:QMarkdownTextEdit will now automatically highlight Markdown syntax (like #, *, -, *bold*, _italic_, code blocks, links) directly in the left-hand editor pane. This is a significant improvement to the editing experience.
Enhanced Editing: Features like tab indentation, duplicating lines, and search/replace should also be improved as provided by the library.
Line Numbers: We explicitly enabled line numbers using sourceEditor->setLineNumberShow(true);.
Now, when you run the application, the left side (editor) will have syntax highlighting, making it much clearer what Markdown you're writing. The right side (previewer) will continue to render the Markdown for you.