Qt - WPS文本编辑器(WPS字体格式)

这篇博客主要介绍了如何在Qt5环境下实现对WPS文本编辑器的字体格式处理,包括在mainwindow.h, mainwindow.cpp, chidwnd.h, childwnd.cpp, main.cpp等文件中的关键操作。通过阅读,读者将了解如何在Qt应用中集成WPS的字体格式功能。" 82776793,4908895,二阶魔方旋转模拟,"['模拟', '算法']
摘要由CSDN通过智能技术生成

WPS字体格式

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
Shift + F5 结束断点调试
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
√选上

在这里插入图片描述

mainwindow.h

在这里插入图片描述

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "childwnd.h"
#include <QSignalMapper>
#include <QWidget>
#include <QMdiSubWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void initMainWindow();
    void docNew();
    void docOpen();
    void docSave();
    void docSaveAs();
    void docUndo();
    void docRedo();
    void docCut();
    void docCopy();
    void docPaste();
    void textBold();
    void textItalic();
    void textUnderline();

private slots:
    void on_newAction_triggered();
    void refreshMenus();
    void addSubWndListMenu();

    void on_closeAction_triggered();

    void on_closeAllAction_triggered();

    void on_titleAction_triggered();

    void on_cascadeAction_triggered();

    void on_nextAction_triggered();

    void on_previousAction_triggered();

    void setActiveSubWindow(QWidget *wnd);

    void on_openAction_triggered();

    void on_saveAction_triggered();

    void on_saveAsAction_triggered();

    void on_undoAction_triggered();

    void on_redoAction_triggered();

    void on_cutAction_triggered();

    void on_copyAction_triggered();

    void on_pasteAction_triggered();

    void on_boldAction_triggered();

    void on_italicAction_triggered();

    void on_underlineAction_triggered();

protected:
    void closeEvent(QCloseEvent *event);

private:
    void formatEnabled();
    ChildWnd* activateChildWnd();
    QMdiSubWindow *findChildWnd(const QString& docName);

private:
    Ui::MainWindow *ui;
    QSignalMapper *m_WndMapper; //信号映射器

};

#endif // MAINWINDOW_H

mainwindow.cpp

在这里插入图片描述

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "childwnd.h"
#include <QFontDatabase>
#include <QMdiSubWindow>
#include <QCloseEvent>
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    initMainWindow();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initMainWindow()
{
    //初始化字号列表项
    QFontDatabase fontdb;
    foreach(int fontsize, fontdb.standardSizes())
    {
        ui->sizeComboBox->addItem(QString::number(fontsize));
    }

    QFont defFont;    //当前应用程序默认的字体
    QString sFontSize;
    int defFontSize;  //当前应用程序默认字体的字号
    int defFontindex; //当前字号在组合框中的索引号

    defFont = QApplication::font();
    defFontSize = defFont.pointSize();
    sFontSize = QString::number(defFontSize);
    defFontindex = ui->sizeComboBox->findText(sFontSize);

    ui->sizeComboBox->setCurrentIndex(defFontindex);

    //设置多文档区域滚动条
    ui->mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    ui->mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    refreshMenus();
    connect(ui->mdiArea, &QMdiArea::subWindowActivated, this, &MainWindow::refreshMenus);

    addSubWndListMenu();
    connect(ui->menu_W, &QMenu::aboutToShow, this, &MainWindow::addSubWndListMenu);

    //创建信号映射器
    m_WndMapper = new QSignalMapper(this);
    connect(m_WndMapper, SIGNAL(mapped(QWidget*)), this, SLOT(setActiveSubWindow(QWidget*)));

}

void MainWindow::docNew()
{
    ChildWnd* childwnd = new ChildWnd;
    ui->mdiArea->addSubWindow(childwnd);
    connect(childwnd, SIGNAL(copyAvailable(bool)), ui->cutAction, SLOT(setEnabled(bool)));
    connect(childwnd, SIGNAL(copyAvailable(bool)), ui->copyAction, SLOT(setEnabled(bool)));

    childwnd->newDoc();
    childwnd->show();
    formatEnabled();
}

void MainWindow::docOpen()
{
    QString docName = QFileDialog::getOpenFileName(this, "打开文档", "", "文本文件(*.txt);;HTML文件(*.html *.htm);;所有文件(*.*)");

    if (!docName.isEmpty())
    {
        QMdiSubWindow *existWnd = findChildWnd(docName);
        if (existWnd)
        {
            ui->mdiArea->setActiveSubWindow(existWnd);
            return;
        }

        ChildWnd *childWnd = new ChildWnd;
        ui->mdiArea->addSubWindow(childWnd);

        connect(childWnd, SIGNAL(copyAvailable(bool)), ui->cutAction, SLOT(setEnabled(bool)));
        connect(childWnd, SIGNAL(copyAvailable(bool)), ui->copyAction, SLOT(setEnabled(bool)));

        if (childWnd->loadDoc(docName))
        {
            statusBar()->showMessage("文档已打开", 3000);
            childWnd->show();
            formatEnabled();
        }
        else
        {
            childWnd->close();
        }
    }
}

void MainWindow::docSave()
{
    if (activateChildWnd() && activateChildWnd()->saveDoc())
    {
        statusBar()->showMessage("保存成功", 3000);
    }
}

void MainWindow::docSaveAs()
{
    if (activateChildWnd() && activateChildWnd()->saveAsDoc())
    {
        statusBar()->showMessage("保存成功", 3000);
    }
}

void MainWindow::docUndo()
{
    if (activateChildWnd())
    {
        activateChildWnd()->undo();
    }
}

void MainWindow::docRedo()
{
    if (activateChildWnd())
        activateChildWnd()->redo();
}

void MainWindow::docCut()
{
    if (activateChildWnd())
        activateChildWnd()->cut();
}

void MainWindow::docCopy()
{
    if (activateChildWnd())
        activateChildWnd()->copy();
}

void MainWindow::docPaste()
{
    if (activateChildWnd())
        activateChildWnd()->paste();
}

void MainWindow::textBold()
{
    QTextCharFormat fmt;
    fmt.setFontWeight(ui->boldAction->isCheckable() ? QFont::Bold : QFont::Normal);
    if (activateChildWnd())
        activateChildWnd()->setFormatOnSelectedWord(fmt);
}

void MainWindow::textItalic()
{
    QTextCharFormat fmt;
    fmt.setFontItalic(ui->italicAction->isChecked());
    if (activateChildWnd())
    {
        activateChildWnd()->setFormatOnSelectedWord(fmt);
    }
}

void MainWindow::textUnderline()
{
    QTextCharFormat fmt;
    fmt.setFontUnderline(ui->underlineAction->isChecked());
    if (activateChildWnd())
    {
        activateChildWnd()->setFormatOnSelectedWord(fmt);
    }
}

void MainWindow::on_newAction_triggered()
{
    docNew();
}

void MainWindow::refreshMenus()
{
    bool hasChild;
    hasChild = (activateChildWnd() != 0);

    ui->saveAction->setEnabled(hasChild);
    ui->saveAsAction->setEnabled(hasChild);
    ui->printAction->setEnabled(hasChild);
    ui->printPreviewAction->setEnabled(hasChild);
    ui->pasteAction->setEnabled(hasChild);
    ui->closeAction->setEnabled(hasChild);
    ui->closeAllAction->setEnabled(hasChild);
    ui->titleAction->setEnabled(hasChild);
    ui->cascadeAction->setEnabled(hasChild);
    ui->nextAction->setEnabled(hasChild);
    ui->previousAction->setEnabled(hasChild);

    //文档打开且有内容选中
    bool hasSelect = ( activateChildWnd() && activateChildWnd()->textCursor().hasSelection() );
    ui->cutAction->setEnabled(hasSelect);
    ui->copyAction->setEnabled(hasSelect);
    ui->boldAction->setEnabled(hasSelect);
    ui->italicAction->setEnabled(hasSelect);
    ui->underlineAction->setEnabled(hasSelect);
    ui->leftAlignAction->setEnabled(hasSelect);
    ui->centerAction->setEnabled(hasSelect);
    ui->rightlignAction->setEnabled(hasSelect);
    ui->justifyAction->setEnabled(hasSelect);
    ui->colorAction->setEnabled(hasSelect);



}

void MainWindow::addSubWndListMenu()
{
    ui->menu_W->clear();
    ui->menu_W->addAction(ui->closeAction);
    ui->menu_W->addAction(ui->closeAllAction);
    ui->menu_W->addSeparator();
    ui->menu_W->addAction(ui->titleAction);
    ui->menu_W->addAction(ui->cascadeAction);
    ui->menu_W->addSeparator();
    ui->menu_W->addAction(ui->nextAction);
    ui->menu_W->addAction(ui->previousAction);


    QList<QMdiSubWindow*> wnds = ui->mdiArea->subWindowList();
    if (!wnds.isEmpty()) ui->menu_W->addSeparator();

    for (int i = 0; i < wnds.size(); ++i)
    {
        ChildWnd *childWnd = qobject_cast<ChildWnd*>(wnds.at(i)->widget());
        QString menuitem_text;
        menuitem_text = QString("%1 %2").arg(i+1).arg(childWnd->getCurDocName());

        QAction *menuitem_act = ui->menu_W->addAction(menuitem_text);
        menuitem_act->setCheckable(true);
        menuitem_act->setChecked(childWnd == activateChildWnd());

        connect(menuitem_act, SIGNAL(triggered(bool)), m_WndMapper, SLOT(map()));

        m_WndMapper->setMapping(menuitem_act, wnds.at(i));
    }

    formatEnabled();
}

void MainWindow::formatEnabled()
{
    ui->boldAction->setEnabled(true);
    ui->italicAction->setEnabled(true);
    ui->underlineAction->setEnabled(true);
    ui->leftAlignAction->setEnabled(true);
    ui->centerAction->setEnabled(true);
    ui->rightlignAction->setEnabled(true);
    ui->justifyAction->setEnabled(true);
    ui->colorAction->setEnabled(true);
}

ChildWnd *MainWindow::activateChildWnd()
{
    QMdiSubWindow* actWnd = ui->mdiArea->activeSubWindow();
    if (actWnd)
        return qobject_cast<ChildWnd*>(actWnd->widget());
    else
        return 0;
}

QMdiSubWindow *MainWindow::findChildWnd(const QString &docName)
{
    QString strFile = QFileInfo(docName).canonicalFilePath();
    foreach(QMdiSubWindow *subWnd, ui->mdiArea->subWindowList())
    {
        ChildWnd *chilWnd = qobject_cast<ChildWnd*>(subWnd->widget());
        if (chilWnd->m_CurDocPath == strFile) return subWnd;
    }

    return 0;
}

//QMdiSubWindow *MainWindow::findChild(const QString &docName)
//{
//    QString strFile = QFileInfo(docName).canonicalFilePath();
//    foreach(QMdiSubWindow *subWnd, ui->mdiArea->subWindowList())
//    {
//        ChildWnd *chilWnd = qobject_cast<ChildWnd*>(subWnd->widget());
//        if (chilWnd->m_CurDocPath == strFile) return subWnd;
//    }

//    return 0;
//}

void MainWindow::on_closeAction_triggered()
{
    ui->mdiArea->closeActiveSubWindow();
}

void MainWindow::on_closeAllAction_triggered()
{
    ui->mdiArea->closeAllSubWindows();
}

void MainWindow::on_titleAction_triggered()
{
    ui->mdiArea->tileSubWindows();
}

void MainWindow::on_cascadeAction_triggered()
{
    ui->mdiArea->cascadeSubWindows();
}

void MainWindow::on_nextAction_triggered()
{
    ui->mdiArea->activateNextSubWindow();
}

void MainWindow::on_previousAction_triggered()
{
    ui->mdiArea->activatePreviousSubWindow();
}

void MainWindow::setActiveSubWindow(QWidget *wnd)
{
    if (!wnd) return;

    ui->mdiArea->setActiveSubWindow(qobject_cast<QMdiSubWindow*>(wnd));

}

void MainWindow::closeEvent(QCloseEvent *event)
{
    ui->mdiArea->closeAllSubWindows();
    if (ui->mdiArea->currentSubWindow())
        event->ignore(); //忽略此事件
    else
        event->accept(); //接收此事件

}

void MainWindow::on_openAction_triggered()
{
    docOpen();
}

void MainWindow::on_saveAction_triggered()
{
    docSave();
}

void MainWindow::on_saveAsAction_triggered()
{
    docSaveAs();
}

void MainWindow::on_undoAction_triggered()
{
    docUndo();
}

void MainWindow::on_redoAction_triggered()
{
    docRedo();
}

void MainWindow::on_cutAction_triggered()
{
    docCut();
}

void MainWindow::on_copyAction_triggered()
{
    docCopy();
}

void MainWindow::on_pasteAction_triggered()
{
    docPaste();
}

void MainWindow::on_boldAction_triggered()
{
    textBold();
}

void MainWindow::on_italicAction_triggered()
{
    textItalic();
}

void MainWindow::on_underlineAction_triggered()
{
    textUnderline();
}

chidwnd.h

在这里插入图片描述

#ifndef CHILDWND_H
#define CHILDWND_H
#include <QTextEdit>

class ChildWnd : public QTextEdit
{
    Q_OBJECT
public:
    ChildWnd();
    QString m_CurDocPath;    //当前文档路径
    void newDoc();           //新建文档
    QString getCurDocName(); //文档路径中提取文档名
    bool loadDoc(const QString& docName);
    void setCurDoc(const QString &docName);
    bool saveDoc();
    bool saveAsDoc();
    bool saveDocOpt(QString docName);
    void setFormatOnSelectedWord(const QTextCharFormat &fmt);

protected:
    void closeEvent(QCloseEvent *event);

private:
    bool promptSave();

public slots:
    void docBeModified();    //文档修改时, 窗口的标题栏加 *

private:
    bool m_bSaved;           //文档是否保存

};

#endif // CHILDWND_H

childwnd.cpp

在这里插入图片描述

#include "childwnd.h"
#include <QFileInfo>
#include <QFileDialog>
#include <QTextDocumentWriter>
#include <QMessageBox>
#include <QCloseEvent>

ChildWnd::ChildWnd()
{
    //子窗口关闭时销毁该类的示例对象
    setAttribute(Qt::WA_DeleteOnClose);

    m_bSaved = false;
}

void ChildWnd::newDoc()
{
    static int wndSepNum = 1;
    m_CurDocPath = QString("WPS 文档%1").arg(wndSepNum++);
    //设置窗体标题, 文档改动后名称后加 "*" 号标识
    setWindowTitle(m_CurDocPath + "[*]" + " - MyWPs");
    connect(document(), SIGNAL(contentsChanged()), this, SLOT(docBeModified()));
}

QString ChildWnd::getCurDocName()
{
    return QFileInfo(m_CurDocPath).fileName();
}

bool ChildWnd::loadDoc(const QString &docName)
{
    if (!docName.isEmpty())
    {
        QFile file(docName);
        if (!file.exists()) return false;

        if (!file.open(QFile::ReadOnly)) return false;
        QByteArray text = file.readAll();
        if (Qt::mightBeRichText(text))
            setHtml(text);
        else
            setPlainText(text);

        setCurDoc(docName);
        connect(document(), SIGNAL(contentsChanged()), this, SLOT(docBeModified()));
        return true;
    }
}

void ChildWnd::setCurDoc(const QString &docName)
{
    //canonicalFilePath() 返回标准名称路径, 可以过滤"." ".."
    m_CurDocPath = QFileInfo(docName).canonicalFilePath();
    m_bSaved = true;                //文档以备保存
    document()->setModified(false); //文档未改动
    setWindowModified(false);       //窗口不显示改动标识
    setWindowTitle(getCurDocName() + "[*]"); //设置子窗口标题
}

bool ChildWnd::saveDoc()
{
    if (m_bSaved) return saveDocOpt(m_CurDocPath);
    else saveAsDoc();
}

bool ChildWnd::saveAsDoc()
{
    QString docName = QFileDialog::getSaveFileName(this, "另存为", m_CurDocPath, "HTML文档 (*.html *.html);;所有文件(*.*)");

    if (docName.isEmpty()) return false;
    else return saveDocOpt(docName);
}

bool ChildWnd::saveDocOpt(QString docName)
{
    if ( !(docName.endsWith(".htm", Qt::CaseInsensitive) || docName.endsWith(".html", Qt::CaseInsensitive)) )
    {
        docName += ".html";
    }

    QTextDocumentWriter writer(docName);
    bool isSuccess = writer.write(this->document());
    if (isSuccess) setCurDoc(docName);
    return isSuccess;
}

void ChildWnd::setFormatOnSelectedWord(const QTextCharFormat &fmt)
{
    QTextCursor tcursor = textCursor();
    if (!tcursor.hasSelection()) tcursor.select(QTextCursor::WordUnderCursor);

    tcursor.mergeCharFormat(fmt);
    mergeCurrentCharFormat(fmt);


}

void ChildWnd::closeEvent(QCloseEvent *event)
{
    if (promptSave())
    {
        event->accept();
    }
    else
    {
        event->ignore();
    }

}

bool ChildWnd::promptSave()
{
    if (! document()->isModified()) return true;

    QMessageBox::StandardButton result;
    result = QMessageBox::warning(this, QString("系统提示"), QString("文档%1已保存, 是否保存?").arg(getCurDocName()),
                                  QMessageBox::Yes | QMessageBox::Discard | QMessageBox::No);

    if (result == QMessageBox::Yes)
        return saveDoc();
    else if (result == QMessageBox::No)
        return false;
    return true;

}

void ChildWnd::docBeModified()
{
    setWindowModified(document()->isModified());
}

main.cpp

没动过

结语:

时间: 2020-08-10

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值