当前位置: 首页 > news >正文

Qt5开发从入门到精通——第五篇四节( 文本编辑器 Easy Word 开发 V1.3详解 )

欢迎小伙伴的点评✨✨,相互学习、互关必回、全天在线🍳🍳🍳
博主🧑🧑 本着开源的精神交流Qt开发的经验、将持续更新续章,为社区贡献博主自身的开源精神👩‍🚀

文章目录

  • 前言
  • 一、Qt 5 文本编辑功能概述
  • 二、基于 Easy Word V1.2 框架进行升级 Easy Word V1.3框架
    • 2.1、实现增加文本编辑模块
    • 2.2、文本编辑器 Easy Word V1.3 槽函数与框架连接解析
  • 三、效果实例
  • 四、原码解析
    • mainwindow.h
    • showwidget.h
    • main.cpp
    • mainwindow.cpp
    • showwidget.cpp
  • 总结


前言

本章节会给大家带来基于文本编辑器 Easy Word V1.2开发升级到Easy Word V1.3开发的解析。


一、Qt 5 文本编辑功能概述

在编写包含格式设置的文本编辑程序时,经常用到的 Qt 类有 QTextEdit、 QTextDocument、
QTextBlock 、 QTextList 、 QTextFrame 、 QTextTable 、 QTextCharFormat 、 QTextBlockFormat 、
QTextListFormat 、 QTextFrameFormat 和 QTextTableFormat 等。
文本编辑各类之间的划分与关系如图一所示。
图一
在这里插入图片描述
任何一个文本编辑的程序都要用 QTextEdit 作为输入文本的容器,在它里面输入可编辑文本由 QTextDocument 作为载体,而用来表示 QTextDocument 的元素的 QTextBlock 、 QTextList 、QTextFrame 等是 QTextDocument 的不同表现形式,可以表示为字符串、段落、列表、表格或图片等。
每种元素都有自己的格式,这些格式则用 QTextCharFormat、 QTextBlockFormat、 QTextListFormat、
QTextFrameFormat 等类来描述与实现。例如, QTextBlockFormat 类对应于 QTextBlock 类, QTextBlock
类用千表示一块文本,通常可以理解为一个段落,但它并不仅指段落; QTextBlockFormat 类则表示这一块文本的格式,如缩进的值、与四边的边距等。
从图一中可以看出,用千表示编辑文本中的光标 QTextCursor 类是一个非常重要且经常用到的类,它提供了对 QTextDocument 文档的修改接口,所有对文档格式的修改,说到底都与光标有关 。 例如,改变字符的格式,实际上指的是改变光标处字符的格式 。 又例如,改变段落的格式,实际上指的是改变光标所在段落的格式。因此,所有对 QTextDocument 的修改都能够通过 QTextCursor 类实现, QTextCursor 类在文档编辑类程序中具有重要的作用 。

二、基于 Easy Word V1.2 框架进行升级 Easy Word V1.3框架

2.1、实现增加文本编辑模块

(1)在 “mainwindow.h” 头文件中添加 “private:” 变量:

    /****************文本编辑功能*****************/

    QLabel *fontLabel1; //字体设置项
    QFontComboBox *fontComboBox;
    QLabel *fontLabel2;
    QComboBox *sizeComboBox;
    QToolButton *boldBtn;
    QToolButton *italicBtn;
    QToolButton *underlineBtn;
    QToolButton *colorBtn;
    QToolBar *fontToolBar; //字体工具栏

(2)在函数createActions()中添加如下代码

    //在工具栏上嵌入控件
    //设置字号
   fontLabel1 =new QLabel (tr("字体:"));
   fontComboBox =new QFontComboBox;
   fontComboBox->setFontFilters(QFontComboBox::ScalableFonts);
   fontLabel2 =new QLabel(tr("字号:"));
   sizeComboBox =new QComboBox;
   QFontDatabase db;
    /***************文本编辑功能******************/
   foreach(int size,db.standardSizes())
   {
       sizeComboBox->addItem(QString::number(size));
   }
   boldBtn =new QToolButton;
   boldBtn->setIcon(QIcon(":/src/bold.png"));
   boldBtn->setCheckable(true);

   italicBtn =new QToolButton;
   italicBtn->setIcon(QIcon(":/src/italic.png"));
   italicBtn->setCheckable(true);


   underlineBtn =new QToolButton;
   underlineBtn->setIcon(QIcon(":/src/underline.png"));
   underlineBtn->setCheckable(true);


   colorBtn =new QToolButton;
   colorBtn->setIcon(QIcon(":/src/color.png"));
   colorBtn->setCheckable(true);
   

(3)在相对应的工具栏 createToolBars() 函数中添加如下代码:

    //字体工具条
    fontToolBar =addToolBar("Font");
    fontToolBar->addWidget(fontLabel1);
    fontToolBar->addWidget(fontComboBox);
    fontToolBar->addWidget(fontLabel2);
    fontToolBar->addWidget(sizeComboBox);
    fontToolBar->addSeparator();
    fontToolBar->addWidget(boldBtn);
    fontToolBar->addWidget (italicBtn);
    fontToolBar->addWidget(underlineBtn);
    fontToolBar->addSeparator();
    fontToolBar->addWidget(colorBtn);

2.2、文本编辑器 Easy Word V1.3 槽函数与框架连接解析

(1)在 “mainwindow.h” 头文件中添加 “private slots:” 变量:

/*****************文本编辑功能****************************/

    void ShowFontComboBox(QString comboStr);
    void ShowSizeSpinBox(QString spinValue);
    void ShowBoldBtn();
    void ShowItalicBtn() ;
    void ShowUnderlineBtn();
    void ShowColorBtn();
    void ShowCurrentFormatChanged(const QTextCharFormat &fmt);

(2)在 createActions() 函数的”“放大“动作“最后添加事件关联:

connect (boldBtn, SIGNAL (clicked()),this,SLOT (ShowBoldBtn()));
connect (italicBtn, SIGNAL (clicked()), this, SLOT (ShowItalicBtn ())) ;
connect (underlineBtn, SIGNAL (clicked()), this, SLOT (ShowUnderlineBtn ()));
connect(colorBtn,SIGNAL(clicked()),this,SLOT(ShowColorBtn()));
connect(fontComboBox,SIGNAL(activated(QString)),this,SLOT(ShowFontComboBox(QString)));
connect(sizeComboBox,SIGNAL(activated(QString)),this,SLOT(ShowSizeSpinBox(QString)));
connect(showWidget->text,SIGNAL(currentCharFormatChanged(QTextCharFormat&)) , this,SLOT(ShowCurrentFormatChanged(QTextCharFormat&)));


(3)实现设置字体的函数 如下:

void MainWindow::ShowFontComboBox(QString comboStr)   //设置字体
{
    QTextCharFormat fmt;             //创建一个 QTextCharFormat 对象
    fmt.setFontFamily(comboStr);    //选择的字体名称设置给 QTextCharFormat 对象
    mergeFormat(fmt);               ///将新的格式应用到光标选区内的字符
}

void MainWindow::mergeFormat(QTextCharFormat format)
{
    QTextCursor cursor =showWidget->text->textCursor ();  //获得编辑框中的光标
    if (!cursor. hasSelection ()) //若光标没有高亮选区,则将光标所在处的词作为选区,由前后空格或",""."等标点符号区分词。
    cursor.select(QTextCursor::WordUnderCursor);
    cursor.mergeCharFormat (format); // 调用 QTextCursor 的 mergeCharFonnatO函数将参数format 所表示的格式应用到光标所在处的字符上。
    showWidget->text->mergeCurrentCharFormat(format); //调用 QTextEdit 的 merge CurrentCharFormat() 
                                                    //函数将格式应用到选区内的所有字符上。
}

void MainWindow::ShowSizeSpinBox(QString spinValue)    //设置字号
{
    QTextCharFormat fmt;
    fmt.setFontPointSize (spinValue.toFloat());
    showWidget->text->mergeCurrentCharFormat(fmt);
}

void MainWindow::ShowBoldBtn()                    //设置文字加粗
{
    QTextCharFormat fmt;
    fmt.setFontWeight(boldBtn->isChecked()?QFont::Bold:QFont:: Normal);
    showWidget->text->mergeCurrentCharFormat(fmt);

	/*其中,调用 QTextCharFormat 的 setFontWeightO函数设置粗细值,若检测到“加粗”按钮被按
下,则设置字符的 Weight 值为 QFont::Bold, 可直接设为 75; 反之,则设为 QFont: :Normal。文字的
粗细值由 QFont::Weight 表示,它是一个整型值,取值的范围可为 0~99, 有 5 个预置值,分别为
QFont::Light(25) 、 QFont::Normal(50) 、 QFont::DemiBold(63) 、 QFont: :Bold(75)和 QFont::Black(87),
通常在 QFont: :Normal 和 QFont::Bold 之间转换。*/

}

void MainWindow::ShowItalicBtn()                //设置文字加下划线
{
    QTextCharFormat fmt;
    fmt.setFontItalic(italicBtn->isChecked());
    showWidget->text->mergeCurrentCharFormat(fmt);
}
void MainWindow::ShowUnderlineBtn()
{
    QTextCharFormat fmt;
    fmt. setFontUnderline (underlineBtn->isChecked ());
    showWidget->text->mergeCurrentCharFormat(fmt);
}

void MainWindow::ShowColorBtn()                 //设置颜色
{
    QColor color=QColorDialog::getColor(Qt::red, this);   //使用了标准颜色对话框的方式,当单击“颜色”按钮时,
                                                          //在弹出的标准颜色对话框中选择颜色。
    if (color. isValid ())
    {
        QTextCharFormat fmt;
        fmt.setForeground(color);
        showWidget->text->mergeCurrentCharFormat(fmt);
    }

	/*标准颜色对话框 QColorDialog 类的使用:
	QColor getColor
	(
		const QColor& initial=Qt::white,
        QWidget* parent=0
	); 
	第 1 个参数指定了选中的颜色,默认为白色。通过 QColor::isValidO可以判断用户选择的颜
色是否有效,若用户单击“取消" (Cancel) 按钮,则 QColor::isValid()返回 false 。第 2 个参数定
义了标准颜色对话框的父窗口。 */
	
}

void MainWindow::ShowCurrentFormatChanged(const QTextCharFormat &fmt)
{
    fontComboBox->setCurrentIndex(fontComboBox->findText(fmt.fontFamily())) ;
    sizeComboBox->setCurrentIndex(sizeComboBox->findText(QString::number(fmt.fontPointSize())));
    boldBtn->setChecked (fmt.font().bold());
    italicBtn->setChecked(fmt.fontItalic());
    underlineBtn->setChecked(fmt.fontUnderline());
}

三、效果实例

图一
在这里插入图片描述
图二
图标和图片放到新建的Resources中

在这里插入图片描述

四、原码解析

工程文件(包含图标)已经上传GitHub,通过git直接拉取即可

git clone https://github.com/dhn111/EasyWord.git

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QImage>
#include <QLabel>
#include <QMenu>
#include <QMenuBar>
#include <QAction>
#include <QComboBox>
#include <QSpinBox>
#include <QToolBar>
#include <QFontComboBox>
#include <QToolButton>
#include <QTextCharFormat>
#include "showwidget.h"
#include <QApplication>
#include <QFileDialog>
#include <QFile>
#include <QTextStream>              //读入文本
#include <QDebug>
#include <QByteArray>
#include <QTextCodec>
#include <QtPrintSupport/QPrintDialog>  //打印文本
#include <QtPrintSupport/QPrinter>
#include <QPainter>               //打印图片
#include <QRect>
#include <QString>
#include <QColorDialog>        //文字颜色
#include <QColor>
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void createActions();       //创建动作
    void createMenus();         //创建菜单
    void createToolBars ();     //创建工具栏
    void loadFile(QString filename);
    void mergeFormat(QTextCharFormat);

private:
    QMenu *fileMenu;                     //各项菜单栏
    QMenu *zoomMenu;
    QMenu *rotateMenu;
    QMenu *mirrorMenu;
    QImage img;
    QString fileName;
    ShowWidget *showWidget;
    QAction *openFileAction;          //文件菜单项
    QAction *NewFileAction;
    QAction *PrintTextAction;
    QAction *PrintImageAction;
    QAction *exitAction;
    QAction *copyAction;           //编辑菜单项
    QAction *cutAction;
    QAction *pasteAction;
    QAction *aboutAction;
    QAction *zoomInAction;
    QAction *zoomOutAction;
    QAction *rotate90Action;       //旋转菜单项
    QAction *rotate180Action;
    QAction *rotate270Action;
    QAction *mirrorVerticalAction;     //镜像菜单项
    QAction *mirrorHorizontalAction;
    QAction *undoAction;
    QAction *redoAction;
    QToolBar *fileTool;              //工具栏
    QToolBar *zoomTool;
    QToolBar *rotateTool;
    QToolBar *mirrorTool;
    QToolBar *doToolBar;

    /****************文本编辑功能*****************/

    QLabel *fontLabel1; //字体设置项
    QFontComboBox *fontComboBox;
    QLabel *fontLabel2;
    QComboBox *sizeComboBox;
    QToolButton *boldBtn;
    QToolButton *italicBtn;
    QToolButton *underlineBtn;
    QToolButton *colorBtn;
    QToolBar *fontToolBar; //字体工具栏




private slots:
    void ShowNewFile();     //新建文件
    void ShowOpenFile();    //打开文件
    void ShowPrintText();   //打印文本
    void ShowPrintImage();  //打印图像
    void ShowZoomIn();      //缩放功能放大
    void ShowZoomOut();     //缩放功能缩小
    void ShowRotate90();    //旋转90°
    void ShowRotate180();   //旋转180°
    void ShowRotate270 ();  //旋转270°
    void ShowMirrorVertical();  //纵向
    void ShowMirrorHorizontal (); //横向



    /*****************文本编辑功能****************************/

    void ShowFontComboBox(QString comboStr);
    void ShowSizeSpinBox(QString spinValue);
    void ShowBoldBtn();
    void ShowItalicBtn() ;
    void ShowUnderlineBtn();
    void ShowColorBtn();
    void ShowCurrentFormatChanged(const QTextCharFormat &fmt);


};

#endif // MAINWINDOW_H

showwidget.h

#ifndef SHOWWIDGET_H
#define SHOWWIDGET_H

#include <QWidget>
#include <QImage>
#include <QLabel>
#include <QTextEdit>
#include <QHBoxLayout>
class ShowWidget : public QWidget
{
    Q_OBJECT
public:
    explicit ShowWidget(QWidget *parent = nullptr);

    QImage img;
    QLabel *imageLabel;
    QTextEdit *text;


signals:

public slots:
};

#endif // SHOWWIDGET_H

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

mainwindow.cpp

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{

    //各项菜单栏
    fileMenu = new QMenu;
    zoomMenu = new QMenu;
    rotateMenu = new QMenu;
    mirrorMenu = new QMenu;
    showWidget = new ShowWidget;


    //文件菜单
    openFileAction =new QAction;
    NewFileAction  =new QAction;
    PrintTextAction =new QAction;
    PrintImageAction =new QAction;
    exitAction       = new QAction;

     //缩放菜单
     copyAction   =new QAction;
     cutAction    =new QAction;
     pasteAction  =new QAction;
     aboutAction  =new QAction;
     zoomInAction =new QAction;
     zoomOutAction=new QAction;

     //旋转菜单项
     rotate90Action =new QAction;
     rotate180Action=new QAction;
     rotate270Action=new QAction;

     //镜像菜单项
     mirrorVerticalAction  =new QAction;
     mirrorHorizontalAction=new QAction;
     undoAction  =new QAction;
     redoAction  =new QAction;

     //工具栏
     fileTool = new  QToolBar;
     zoomTool = new  QToolBar;
     rotateTool = new  QToolBar;
     mirrorTool = new  QToolBar;
     doToolBar = new  QToolBar;


    setWindowTitle(tr("Easy Word"));  //设置窗体标题
    showWidget =new ShowWidget(this); //(a)
    setCentralWidget(showWidget);


    /*创建动作、菜单、工具栏的函数*/
    createActions() ;
    createMenus();
    createToolBars();
    if(img.load(":/src/PKQ.png"))
    {
        //在 imageLabel 对象中放置图片
        showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
    }
}

MainWindow::~MainWindow()
{

}

void MainWindow::createActions()
{
    //“打开”动作
    openFileAction =new QAction(QIcon(":/src/open.png"),tr("打开"),this);  //(a)
    openFileAction->setShortcut (tr ("Ctrl+O"));                      //(b)
    openFileAction->setStatusTip(tr("打开一个文件 "));                 //(c)
    connect(openFileAction,SIGNAL(triggered()),this,SLOT(ShowOpenFile()));
    //"新建“动作
    NewFileAction =new QAction(QIcon(":/src/new.png"),tr("新建"),this);
    NewFileAction->setShortcut(tr("Ctrl+N"));
    NewFileAction->setStatusTip(tr("新建一个文件"));
    connect(NewFileAction, SIGNAL (triggered()) , this, SLOT (ShowNewFile())) ;
    // "退出“动作
    exitAction =new QAction(tr("退出"),this);
    exitAction->setShortcut(tr("Ctrl+Q"));
    exitAction->setStatusTip(tr("退出程序")) ;
    connect (exitAction, SIGNAL (triggered()), this, SLOT (close()));
    // "复制”动作
    copyAction =new QAction(QIcon(":/src/copy.png"),tr("复制"),this);
    copyAction->setShortcut(tr("Ctrl+C"));
    copyAction->setStatusTip(tr(" 复制文件")) ;
    connect(copyAction,SIGNAL( triggered ()), showWidget->text, SLOT(copy()));
    //"剪切“动作
    cutAction =new QAction(QIcon(":/src/cut.png"),tr("剪切"),this);
    cutAction->setShortcut(tr("Ctrl+X"));
    cutAction->setStatusTip(tr("剪切文件")) ;
    connect(cutAction,SIGNAL( triggered ()), showWidget->text, SLOT (cut()));
    //"粘贴“动作
    pasteAction =new QAction(QIcon(":/src/paste.png"),tr("粘贴"),this);
    pasteAction->setShortcut(tr("Ctrl+V"));
    pasteAction->setStatusTip(tr("粘贴文件")) ;
    connect(pasteAction,SIGNAL(triggered()),showWidget->text,SLOT (paste()));
    //"关于“动作
    aboutAction =new QAction(tr("关于"),this);
    connect(aboutAction,SIGNAL(triggered()),this,SLOT(QApplication::aboutQt()));
    //"打印文本“动作
    PrintTextAction =new QAction(QIcon(":/src/printText.png"),tr(" 打印文本"), this);
    PrintTextAction->setStatusTip(tr("打印一个文本"));
    connect (PrintTextAction, SIGNAL (triggered()), this, SLOT (ShowPrintText ()));
    //"打印图片“动作
    PrintImageAction =new QAction(QIcon (":/src/printimage.png" ), tr("打印图片"), this);
    PrintImageAction->setStatusTip(tr("打印一幅图片"));
    connect(PrintImageAction, SIGNAL (triggered()), this, SLOT (ShowPrintImage()));
    //"放大“动作
    zoomInAction =new QAction (QIcon(":/src/zoomin.png"),tr(" 放大 "),this);
    zoomInAction->setStatusTip(tr("放大一幅图片"));
    connect(zoomInAction,SIGNAL(triggered()),this,SLOT(ShowZoomIn()));
    //"缩小“动作
    zoomOutAction =new QAction(QIcon(":/src/zoomout.png"),tr("缩小 "),this);
    zoomOutAction->setStatusTip(tr("缩小一幅图片 "));
    connect (zoomOutAction, SIGNAL(triggered ()), this, SLOT (ShowZoomOut()));
    //实现图片旋转的动作 (Action)
    //旋转 90°
    rotate90Action =new QAction (QIcon (":/src/rotate90.png"), tr("旋转 90°") ,this);
    rotate90Action->setStatusTip(tr("将一幅图旋转90°"));
    connect(rotate90Action, SIGNAL (triggered()), this, SLOT (ShowRotate90()));
    //旋转180°
    rotate180Action =new QAction (QIcon(":/src/rotate180.png"), tr("旋转 180°"), this);
    rotate180Action->setStatusTip(tr("将一幅图旋转180°"));
    connect(rotate180Action, SIGNAL (triggered()), this, SLOT (ShowRotate180()));
    //旋转270°
    rotate270Action =new QAction(QIcon (":/src/rotate270.png"), tr("旋转 270°"), this);
    rotate270Action->setStatusTip(tr("将一幅图旋转 270°"));
    connect(rotate270Action, SIGNAL (triggered()), this, SLOT (ShowRotate270()));
    //实现图片镜像的动作(Action)
    //纵向镜像
    mirrorVerticalAction =new QAction(QIcon(":/src/mirrorVertical.png"),tr("纵向镜像"), this);
    mirrorVerticalAction->setStatusTip(tr("对一幅图做纵向镜像")) ;
    connect (mirrorVerticalAction, SIGNAL (triggered()), this, SLOT (ShowMirrorVertical()));
    //横向镜像
    mirrorHorizontalAction =new QAction(QIcon(":/src/mirrorHorizontal.png"),tr("横向镜像 "),this);
    mirrorHorizontalAction->setStatusTip(tr("对一幅图做横向镜像")) ;
    connect (mirrorHorizontalAction, SIGNAL (triggered()), this, SLOT (ShowMirrorHorizontal ()));
    //实现撤销和重做的动作(ACtion)
    //撤销和重做
    undoAction =new QAction (QIcon(":/src/undo.png"),"撤销",this);
    connect(undoAction,SIGNAL(triggered()),showWidget->text,SLOT(undo()));
    redoAction =new QAction(QIcon(":/src/redo.png"),"重做",this);
    connect(redoAction, SIGNAL(triggered()),showWidget->text,SLOT(redo()));


    //在工具栏上嵌入控件
    //设置字号
   fontLabel1 =new QLabel (tr("字体:"));
   fontComboBox =new QFontComboBox;
   fontComboBox->setFontFilters(QFontComboBox::ScalableFonts);
   fontLabel2 =new QLabel(tr("字号:"));
   sizeComboBox =new QComboBox;
   QFontDatabase db;
    /***************文本编辑功能******************/
   foreach(int size,db.standardSizes())
   {
       sizeComboBox->addItem(QString::number(size));
   }
   boldBtn =new QToolButton;
   boldBtn->setIcon(QIcon(":/src/bold.png"));
   boldBtn->setCheckable(true);
   connect (boldBtn, SIGNAL (clicked()),this,SLOT (ShowBoldBtn()));

   italicBtn =new QToolButton;
   italicBtn->setIcon(QIcon(":/src/italic.png"));
   italicBtn->setCheckable(true);
   connect (italicBtn, SIGNAL (clicked()), this, SLOT (ShowItalicBtn ())) ;

   underlineBtn =new QToolButton;
   underlineBtn->setIcon(QIcon(":/src/underline.png"));
   underlineBtn->setCheckable(true);
   connect (underlineBtn, SIGNAL (clicked()), this, SLOT (ShowUnderlineBtn ()));

   colorBtn =new QToolButton;
   colorBtn->setIcon(QIcon(":/src/color.png"));
   colorBtn->setCheckable(true);
   connect(colorBtn,SIGNAL(clicked()),this,SLOT(ShowColorBtn()));


   connect(fontComboBox,SIGNAL(activated(QString)),this,SLOT(ShowFontComboBox(QString)));
   connect(sizeComboBox,SIGNAL(activated(QString)),this,SLOT(ShowSizeSpinBox(QString)));





   connect(showWidget->text,SIGNAL(currentCharFormatChanged(QTextCharFormat&)) , this,SLOT(ShowCurrentFormatChanged(const QTextCharFormat &fmt)));

}

void MainWindow::createMenus()
{
    //文件菜单

    fileMenu =menuBar()->addMenu(tr("文件")) ;
    fileMenu->addAction(openFileAction);
    fileMenu->addAction(NewFileAction);
    fileMenu->addAction(PrintTextAction);
    fileMenu->addAction(PrintImageAction);
    fileMenu->addSeparator();
    fileMenu->addAction(exitAction);
    //缩放菜单

    zoomMenu =menuBar()->addMenu(tr("编辑")) ;
    zoomMenu->addAction(copyAction);
    zoomMenu->addAction(cutAction);
    zoomMenu->addAction(pasteAction);
    zoomMenu->addAction(aboutAction);
    zoomMenu->addSeparator();
    zoomMenu->addAction(zoomInAction);
    zoomMenu->addAction(zoomOutAction);
    //旋转菜单
    rotateMenu =menuBar ()->addMenu(tr("旋转")) ;
    rotateMenu->addAction(rotate90Action);
    rotateMenu->addAction(rotate180Action);
    rotateMenu->addAction(rotate270Action);
    //镜像菜单
    mirrorMenu =menuBar()->addMenu(tr(" 镜像")) ;
    mirrorMenu->addAction(mirrorVerticalAction);
    mirrorMenu->addAction(mirrorHorizontalAction);
}


void MainWindow::createToolBars()
{
    //文件工具条
    fileTool =addToolBar("File");
    fileTool->addAction(openFileAction);
    fileTool->addAction(NewFileAction);
    fileTool->addAction(PrintTextAction);
    fileTool->addAction(PrintImageAction);
    //编辑工具条
    zoomTool =addToolBar("Edit");
    zoomTool->addAction(copyAction);
    zoomTool->addAction(cutAction);
    zoomTool->addAction(pasteAction);
    zoomTool->addSeparator();
    zoomTool->addAction(zoomInAction);
    zoomTool->addAction(zoomOutAction);
    //旋转工具条
    rotateTool =addToolBar("rotate");
    rotateTool->addAction(rotate90Action);
    rotateTool->addAction(rotate180Action);
    rotateTool->addAction(rotate270Action);
    //撤销和重做工具条
    doToolBar =addToolBar("doEdit");
    doToolBar->addAction(undoAction);
    doToolBar->addAction(redoAction);

    //字体工具条
    fontToolBar =addToolBar("Font");
    fontToolBar->addWidget(fontLabel1);
    fontToolBar->addWidget(fontComboBox);
    fontToolBar->addWidget(fontLabel2);
    fontToolBar->addWidget(sizeComboBox);
    fontToolBar->addSeparator();
    fontToolBar->addWidget(boldBtn);
    fontToolBar->addWidget (italicBtn);
    fontToolBar->addWidget(underlineBtn);
    fontToolBar->addSeparator();
    fontToolBar->addWidget(colorBtn);

}

void MainWindow::ShowNewFile()                  //新建文件的槽
{
    MainWindow *newMainWindow =new MainWindow;
    newMainWindow->show();
}

void MainWindow::ShowOpenFile()                  //读取文件的槽
{
    fileName =QFileDialog::getOpenFileName(this);
    if(!fileName.isEmpty())
    {
        if(showWidget->text->document()->isEmpty())
        {
            loadFile(fileName);
        }else
        {
            MainWindow *newMainWindows = new MainWindow;
            newMainWindows->show();
            newMainWindows->loadFile(fileName);
        }


    }
}


#if 1
void MainWindow::loadFile(QString filename)
{

     QFile  file(filename);

    if(file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
         QTextStream textStream(&file);
        while(!textStream.atEnd())
        {


            showWidget->text->append(textStream.readLine());


        }


    }
}
#endif


#if 0
void MainWindow::loadFile(QString filename)
{

     QFile  file(filename);
     QTextCodec *codec = QTextCodec::codecForName("GBK");
    if(file.open(QIODevice::ReadOnly|QIODevice::Text))
    {

        while(!file.atEnd())
        {
            QByteArray line = file.readLine();
            QString str = codec->toUnicode(line);
            showWidget->text->append(str);

            //qDebug()<<textStream.readLine();

        }


    }
}
#endif

void MainWindow::ShowPrintText()             //文本打印
{
    QPrinter printer;
    QPrintDialog printDialog(&printer,this);
    if(printDialog.exec())
    {
        //获得QTextEdit对象的文档
        QTextDocument *doc =showWidget->text->document();
        doc->print(&printer); //打印
    }
}

void MainWindow::ShowPrintImage()           //图像打印
{
    QPrinter printer;
    QPrintDialog printDialog(&printer,this);
    if(printDialog.exec())
    {
        QPainter painter(&printer);
        QRect rect =painter.viewport();   //获得QPainter对象的视图矩形区域
        QSize size = img.size();          //获得图像的大小
        /*按照图形的比例大小重新设置视图矩形区域*/
        size.scale(rect.size(), Qt::KeepAspectRatio);
        painter.setViewport(rect.x(),rect.y(),size.width(),size.height());
        painter.setWindow(img.rect());
        painter.drawImage(0,0,img);

    }
}

void MainWindow::ShowZoomIn()          //图像放大
{
    if(img.isNull())     //有效性判断
    {
        return;
    }

    QMatrix matrix;     //声明一个QMatrix类的实例
    matrix.scale(2,2);
    img = img.transformed(matrix);
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));


}

void MainWindow::ShowZoomOut()      //图像缩小
{
    if (img.isNull())
    {
        return;
    }
    QMatrix matrix;
    matrix.scale(0.5,0.5);
    img=img.transformed(matrix);
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));


}

void MainWindow::ShowRotate90()                  //旋转90°
{
    if(img.isNull())
    {
        return;
    }
    QMatrix matrix;
    matrix.rotate(90);
    img = img.transformed(matrix);
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));

}


void MainWindow::ShowRotate180()        //旋转180°
{
    if(img.isNull())
    {
        return;
    }
    QMatrix matrix;
    matrix.rotate(180);
    img = img.transformed(matrix);
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
}

void MainWindow::ShowRotate270()      //旋转270°
{
    if(img.isNull())
    {
        return;
    }
    QMatrix matrix;
    matrix.rotate(270);
    img = img.transformed(matrix);
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
}

void MainWindow::ShowMirrorVertical()   //纵向镜像
{
    if(img. isNull ())
    return;
    img=img.mirrored(false,true);
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
}
void MainWindow::ShowMirrorHorizontal() //横向镜像
{
    if(img. isNull ())
    return;
    img=img.mirrored(true,false);
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
}


void MainWindow::ShowFontComboBox(QString comboStr)
{
    QTextCharFormat fmt;             //设置字体
    fmt.setFontFamily(comboStr);
    mergeFormat(fmt);
}

void MainWindow::mergeFormat(QTextCharFormat format)
{
    QTextCursor cursor =showWidget->text->textCursor ();  //获得编辑框中的光标
    if (!cursor. hasSelection ()) //(a)
    cursor.select(QTextCursor::WordUnderCursor);
    cursor.mergeCharFormat (format); // (b)
    showWidget->text->mergeCurrentCharFormat(format); //(c)
}

void MainWindow::ShowSizeSpinBox(QString spinValue)
{
    QTextCharFormat fmt;
    fmt.setFontPointSize (spinValue.toFloat());
    showWidget->text->mergeCurrentCharFormat(fmt);
}

void MainWindow::ShowBoldBtn()
{
    QTextCharFormat fmt;
    fmt.setFontWeight(boldBtn->isChecked()?QFont::Bold:QFont:: Normal);
    showWidget->text->mergeCurrentCharFormat(fmt);
}

void MainWindow::ShowItalicBtn()
{
    QTextCharFormat fmt;
    fmt.setFontItalic(italicBtn->isChecked());
    showWidget->text->mergeCurrentCharFormat(fmt);
}
void MainWindow::ShowUnderlineBtn()
{
    QTextCharFormat fmt;
    fmt. setFontUnderline (underlineBtn->isChecked ());
    showWidget->text->mergeCurrentCharFormat(fmt);
}

void MainWindow::ShowColorBtn()
{
    QColor color=QColorDialog::getColor(Qt::red, this);
    if (color. isValid ())
    {
        QTextCharFormat fmt;
        fmt.setForeground(color);
        showWidget->text->mergeCurrentCharFormat(fmt);
    }
}

void MainWindow::ShowCurrentFormatChanged(const QTextCharFormat &fmt)
{
    fontComboBox->setCurrentIndex(fontComboBox->findText(fmt.fontFamily())) ;
    sizeComboBox->setCurrentIndex(sizeComboBox->findText(QString::number(fmt.fontPointSize())));
    boldBtn->setChecked (fmt.font().bold());
    italicBtn->setChecked(fmt.fontItalic());
    underlineBtn->setChecked(fmt.fontUnderline());
}

showwidget.cpp

#include "showwidget.h"

ShowWidget::ShowWidget(QWidget *parent) : QWidget(parent)
{
    imageLabel =new QLabel;
    imageLabel->setScaledContents( true);
    text =new QTextEdit;
    QHBoxLayout *mainLayout =new QHBoxLayout(this);
    mainLayout->addWidget(imageLabel);
    mainLayout->addWidget(text);
}


总结

窗口构成会在应用程序开发中经常用到的

相关文章:

  • c#-WPF使用类和子类绑定到DataContext
  • 图像隐写,如何在图像中隐藏二维码
  • SPL工业智能:发现时序数据的异常
  • 【Linux】进程概念(万字详解)—— 冯诺依曼体系结构 | 操作系统 | 进程
  • 网络编程套接字-----实现网络间通信
  • 机器学习:详细推导支持向量机SVM原理+Python实现
  • mysql socket文件丢失处理或者mysql.sock被删除
  • 欧拉计划详解第506题:钟摆序列
  • 《Python3 网络爬虫开发实战》:二、HTML消息结构
  • 调试接口小技巧-通过接口调试工具去下载上传文件
  • 【C指针详解】进阶篇
  • 惊奇发现业务移动端在往小程序化发展
  • 啸叫检测的方法:基于DSP的实现
  • java中比较两个map是否相同
  • C/C++编程工具及实用小软件推荐
  • 《剑指offer》分解让复杂问题更简单
  • C++回声服务器_9-epoll边缘触发模式版本服务器
  • create-react-app项目添加less配置
  • JavaWeb(学习笔记二)
  • JS正则表达式精简教程(JavaScript RegExp 对象)
  • leetcode-27. Remove Element
  • Lsb图片隐写
  • Redash本地开发环境搭建
  • SQLServer之创建显式事务
  • Swift 中的尾递归和蹦床
  • Three.js 再探 - 写一个跳一跳极简版游戏
  • vagrant 添加本地 box 安装 laravel homestead
  • 不发不行!Netty集成文字图片聊天室外加TCP/IP软硬件通信
  • 动手做个聊天室,前端工程师百无聊赖的人生
  • 基于MaxCompute打造轻盈的人人车移动端数据平台
  • 基于游标的分页接口实现
  • 猫头鹰的深夜翻译:Java 2D Graphics, 简单的仿射变换
  • 面试题:给你个id,去拿到name,多叉树遍历
  • 排序算法学习笔记
  • 前端自动化解决方案
  • 腾讯视频格式如何转换成mp4 将下载的qlv文件转换成mp4的方法
  • 小程序开发中的那些坑
  • 阿里云服务器如何修改远程端口?
  • ​flutter 代码混淆
  • ​软考-高级-系统架构设计师教程(清华第2版)【第15章 面向服务架构设计理论与实践(P527~554)-思维导图】​
  • (附源码)基于ssm的模具配件账单管理系统 毕业设计 081848
  • (附源码)计算机毕业设计ssm高校《大学语文》课程作业在线管理系统
  • (六)激光线扫描-三维重建
  • (一) storm的集群安装与配置
  • (一)【Jmeter】JDK及Jmeter的安装部署及简单配置
  • (转)Groupon前传:从10个月的失败作品修改,1个月找到成功
  • (转)Mysql的优化设置
  • ... fatal error LINK1120:1个无法解析的外部命令 的解决办法
  • ./和../以及/和~之间的区别
  • .NET Core WebAPI中使用Log4net 日志级别分类并记录到数据库
  • .NET Micro Framework初体验
  • .NET 分布式技术比较
  • .NET 使用 ILRepack 合并多个程序集(替代 ILMerge),避免引入额外的依赖
  • .NET/C# 利用 Walterlv.WeakEvents 高性能地定义和使用弱事件
  • .NET/C# 利用 Walterlv.WeakEvents 高性能地中转一个自定义的弱事件(可让任意 CLR 事件成为弱事件)