0


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

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

文章目录


前言

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


一、基于 Easy Word V1.3 框架进行升级 Easy Word V1.4框架

1.1、实现增加排版模块

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

/******************排版功能************************/

    QLabel *listLabel;
    QComboBox *listComboBox;
    QActionGroup *actGrp;
    QAction *leftAction;
    QAction *rightAction;
    QAction *centerAction;
    QAction *justifyAction;
    QToolBar *listToolBar;

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

/************排版功能********************************/voidShowList(int);voidShowAlignment(QAction *act);voidShowCursorPositionChanged();

(3) 在相对应的构造函数中,在语句 “setCentralWidget(showWidget);” 与语句 "createActions() ; "之间添加如下代码:

/*****************排版**********************************/
    listLabel =newQLabel(tr("排序"));
    listComboBox =new QComboBox;
    listComboBox->addItem("Standard");
    listComboBox->addItem("QTextListFormat::ListDisc");
    listComboBox->addItem("QTextListFormat::ListCircle");
    listComboBox->addItem("QTextListFormat::ListSquare");
    listComboBox->addItem("QTextListFormat::ListDecimal");
    listComboBox->addItem("QTextListFormat::ListLowerAlpha");
    listComboBox->addItem("QTextListFormat::ListUpperAlpha");
    listComboBox->addItem("QTextListFormat::ListLowerRoman");
    listComboBox->addItem("QTextListFormat::ListUpperRoman");connect(listComboBox,SIGNAL(activated(int)),this,SLOT(ShowList(int)));connect(showWidget->text->document(),SIGNAL(undoAvailable(bool)),redoAction,SLOT(setEnabled(bool)));connect(showWidget->text->document(),SIGNAL(redoAvailable(bool)),redoAction,SLOT(setEnabled(bool)));connect(showWidget->text,SIGNAL(cursorPositionChanged()),this,SLOT(ShowCursorPositionChanged()));

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

/******************排版功能********************************///左对齐、右对齐、居中和两端对齐
   actGrp =newQActionGroup(this);
   leftAction =newQAction(QIcon(":/src/left.png"),"左对齐",actGrp);
  
   leftAction->setCheckable(true);
   rightAction =newQAction(QIcon(":/src/right.png"),"右对齐 ",actGrp);
   rightAction->setCheckable(true);
   centerAction =newQAction(QIcon(":/src/center.png")," 居中", actGrp);
   centerAction->setCheckable(true);
   justifyAction =newQAction(QIcon(":/src/justify.png"),"两端对齐 ",actGrp);
   justifyAction->setCheckable(true);connect(actGrp,SIGNAL(triggered(QAction*)),this,SLOT(ShowAlignment(QAction*)));

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

    listToolBar =addToolBar("list");
    listToolBar->addWidget(listLabel);
    listToolBar->addWidget(listComboBox);
    listToolBar->addSeparator();
    listToolBar->addActions(actGrp->actions())

1.2、槽函数实现段落对齐

完成对按下某个对齐按钮的响应使用 ShowAlignmentO函数,根据比较判断触发的是哪个对齐按钮,调用 QTextEdit 的 setAlignment()函数可以实现当前段落的对齐调整。响应文本中光标位置处发生改变的信号的 ShowCursorPositionChanged()函数。

/********************排版编辑********************************/voidMainWindow::ShowAlignment(QAction *act)//当前段落对齐{if(act==leftAction)
    showWidget->text->setAlignment(Qt::AlignLeft);if(act==rightAction)
    showWidget->text->setAlignment(Qt::AlignRight);if(act==centerAction)
    showWidget->text->setAlignment(Qt::AlignCenter);if(act==justifyAction)
    showWidget->text->setAlignment(Qt::AlignJustify);}voidMainWindow::ShowCursorPositionChanged(){if(showWidget->text->alignment()==Qt::AlignLeft)
    leftAction->setChecked(true);if(showWidget->text->alignment()==Qt::AlignRight)
    rightAction->setChecked(true);if(showWidget->text->alignment()==Qt::AlignCenter)
    centerAction->setChecked(true);if(showWidget->text->alignment()==Qt::AlignJustify)
    justifyAction->setChecked(true);}voidMainWindow::ShowList(int index)//实现文本排序{///获得编辑框的 QTextCursor 对象指针
    QTextCursor cursor=showWidget->text->textCursor();if(index!=0){
        QTextListFormat::Style style=QTextListFormat:: ListDisc;switch(index){default:case1:
        style=QTextListFormat::ListDisc;break;case2:
        style=QTextListFormat::ListCircle;break;case3:
        style=QTextListFormat::ListSquare;break;case4:
        style=QTextListFormat::ListDecimal;break;case5:

        style=QTextListFormat::ListLowerAlpha;break;case6:
        style=QTextListFormat::ListUpperAlpha;break;case7:
        style=QTextListFormat::ListLowerRoman;break;case8:
        style=QTextListFormat::ListUpperRoman;break;}//设置缩进
        cursor.beginEditBlock();
        QTextBlockFormat blockFmt=cursor.blockFormat();
        QTextListFormat listFmt;if(cursor.currentList()){
            listFmt=cursor.currentList()->format();}else{
            listFmt.setIndent(blockFmt.indent()+1);
            blockFmt.setIndent(0);
            cursor.setBlockFormat(blockFmt);}

        listFmt.setStyle(style);
        cursor.createList(listFmt);
        cursor.endEditBlock();}else{
        QTextBlockFormat bfmt;
        bfmt.setObjectIndex(-1);
        cursor.mergeBlockFormat(bfmt);}}

二、效果实例

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

在这里插入图片描述

三、原码解析

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

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

mainwindow.h

#ifndefMAINWINDOW_H#defineMAINWINDOW_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>#include<QActionGroup>//排版功能#include<QTextList>classMainWindow:publicQMainWindow{
    Q_OBJECT

public:MainWindow(QWidget *parent =0);~MainWindow();voidcreateActions();//创建动作voidcreateMenus();//创建菜单voidcreateToolBars();//创建工具栏voidloadFile(QString filename);voidmergeFormat(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;//字体工具栏/******************排版功能************************/

    QLabel *listLabel;
    QComboBox *listComboBox;
    QActionGroup *actGrp;
    QAction *leftAction;
    QAction *rightAction;
    QAction *centerAction;
    QAction *justifyAction;
    QToolBar *listToolBar;private slots:voidShowNewFile();//新建文件voidShowOpenFile();//打开文件voidShowPrintText();//打印文本voidShowPrintImage();//打印图像voidShowZoomIn();//缩放功能放大voidShowZoomOut();//缩放功能缩小voidShowRotate90();//旋转90°voidShowRotate180();//旋转180°voidShowRotate270();//旋转270°voidShowMirrorVertical();//纵向voidShowMirrorHorizontal();//横向/*****************文本编辑功能****************************/voidShowFontComboBox(QString comboStr);voidShowSizeSpinBox(QString spinValue);voidShowBoldBtn();voidShowItalicBtn();voidShowUnderlineBtn();voidShowColorBtn();voidShowCurrentFormatChanged(const QTextCharFormat &fmt);/************排版功能********************************/voidShowList(int);voidShowAlignment(QAction *act);voidShowCursorPositionChanged();};#endif// MAINWINDOW_H

showwidget.h

#ifndefSHOWWIDGET_H#defineSHOWWIDGET_H#include<QWidget>#include<QImage>#include<QLabel>#include<QTextEdit>#include<QHBoxLayout>classShowWidget:publicQWidget{
    Q_OBJECT
public:explicitShowWidget(QWidget *parent =nullptr);

    QImage img;
    QLabel *imageLabel;
    QTextEdit *text;

signals:public slots:};#endif// SHOWWIDGET_H

main.cpp

#include"mainwindow.h"#include<QApplication>intmain(int argc,char*argv[]){
    QApplication a(argc, argv);
    QFont f("ZYSong18030",12);
    a.setFont(f);
    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 =newShowWidget(this);//(a)setCentralWidget(showWidget);/*****************排版**********************************/
    listLabel =newQLabel(tr("排序"));
    listComboBox =new QComboBox;
    listComboBox->addItem("Standard");
    listComboBox->addItem("QTextListFormat::ListDisc");
    listComboBox->addItem("QTextListFormat::ListCircle");
    listComboBox->addItem("QTextListFormat::ListSquare");
    listComboBox->addItem("QTextListFormat::ListDecimal");
    listComboBox->addItem("QTextListFormat::ListLowerAlpha");
    listComboBox->addItem("QTextListFormat::ListUpperAlpha");
    listComboBox->addItem("QTextListFormat::ListLowerRoman");
    listComboBox->addItem("QTextListFormat::ListUpperRoman");connect(listComboBox,SIGNAL(activated(int)),this,SLOT(ShowList(int)));connect(showWidget->text->document(),SIGNAL(undoAvailable(bool)),redoAction,SLOT(setEnabled(bool)));connect(showWidget->text->document(),SIGNAL(redoAvailable(bool)),redoAction,SLOT(setEnabled(bool)));connect(showWidget->text,SIGNAL(cursorPositionChanged()),this,SLOT(ShowCursorPositionChanged()));/*创建动作、菜单、工具栏的函数*/createActions();createMenus();createToolBars();if(img.load(":/src/PKQ.png")){//在 imageLabel 对象中放置图片
        showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));}}MainWindow::~MainWindow(){}voidMainWindow::createActions(){//“打开”动作
    openFileAction =newQAction(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 =newQAction(QIcon(":/src/new.png"),tr("新建"),this);
    NewFileAction->setShortcut(tr("Ctrl+N"));
    NewFileAction->setStatusTip(tr("新建一个文件"));connect(NewFileAction,SIGNAL(triggered()),this,SLOT(ShowNewFile()));// "退出“动作
    exitAction =newQAction(tr("退出"),this);
    exitAction->setShortcut(tr("Ctrl+Q"));
    exitAction->setStatusTip(tr("退出程序"));connect(exitAction,SIGNAL(triggered()),this,SLOT(close()));// "复制”动作
    copyAction =newQAction(QIcon(":/src/copy.png"),tr("复制"),this);
    copyAction->setShortcut(tr("Ctrl+C"));
    copyAction->setStatusTip(tr(" 复制文件"));connect(copyAction,SIGNAL(triggered()), showWidget->text,SLOT(copy()));//"剪切“动作
    cutAction =newQAction(QIcon(":/src/cut.png"),tr("剪切"),this);
    cutAction->setShortcut(tr("Ctrl+X"));
    cutAction->setStatusTip(tr("剪切文件"));connect(cutAction,SIGNAL(triggered()), showWidget->text,SLOT(cut()));//"粘贴“动作
    pasteAction =newQAction(QIcon(":/src/paste.png"),tr("粘贴"),this);
    pasteAction->setShortcut(tr("Ctrl+V"));
    pasteAction->setStatusTip(tr("粘贴文件"));connect(pasteAction,SIGNAL(triggered()),showWidget->text,SLOT(paste()));//"关于“动作
    aboutAction =newQAction(tr("关于"),this);connect(aboutAction,SIGNAL(triggered()),this,SLOT(QApplication::aboutQt()));//"打印文本“动作
    PrintTextAction =newQAction(QIcon(":/src/printText.png"),tr(" 打印文本"),this);
    PrintTextAction->setStatusTip(tr("打印一个文本"));connect(PrintTextAction,SIGNAL(triggered()),this,SLOT(ShowPrintText()));//"打印图片“动作
    PrintImageAction =newQAction(QIcon(":/src/printimage.png"),tr("打印图片"),this);
    PrintImageAction->setStatusTip(tr("打印一幅图片"));connect(PrintImageAction,SIGNAL(triggered()),this,SLOT(ShowPrintImage()));//"放大“动作
    zoomInAction =newQAction(QIcon(":/src/zoomin.png"),tr(" 放大 "),this);
    zoomInAction->setStatusTip(tr("放大一幅图片"));connect(zoomInAction,SIGNAL(triggered()),this,SLOT(ShowZoomIn()));//"缩小“动作
    zoomOutAction =newQAction(QIcon(":/src/zoomout.png"),tr("缩小 "),this);
    zoomOutAction->setStatusTip(tr("缩小一幅图片 "));connect(zoomOutAction,SIGNAL(triggered()),this,SLOT(ShowZoomOut()));//实现图片旋转的动作 (Action)//旋转 90°
    rotate90Action =newQAction(QIcon(":/src/rotate90.png"),tr("旋转 90°"),this);
    rotate90Action->setStatusTip(tr("将一幅图旋转90°"));connect(rotate90Action,SIGNAL(triggered()),this,SLOT(ShowRotate90()));//旋转180°
    rotate180Action =newQAction(QIcon(":/src/rotate180.png"),tr("旋转 180°"),this);
    rotate180Action->setStatusTip(tr("将一幅图旋转180°"));connect(rotate180Action,SIGNAL(triggered()),this,SLOT(ShowRotate180()));//旋转270°
    rotate270Action =newQAction(QIcon(":/src/rotate270.png"),tr("旋转 270°"),this);
    rotate270Action->setStatusTip(tr("将一幅图旋转 270°"));connect(rotate270Action,SIGNAL(triggered()),this,SLOT(ShowRotate270()));//实现图片镜像的动作(Action)//纵向镜像
    mirrorVerticalAction =newQAction(QIcon(":/src/mirrorVertical.png"),tr("纵向镜像"),this);
    mirrorVerticalAction->setStatusTip(tr("对一幅图做纵向镜像"));connect(mirrorVerticalAction,SIGNAL(triggered()),this,SLOT(ShowMirrorVertical()));//横向镜像
    mirrorHorizontalAction =newQAction(QIcon(":/src/mirrorHorizontal.png"),tr("横向镜像 "),this);
    mirrorHorizontalAction->setStatusTip(tr("对一幅图做横向镜像"));connect(mirrorHorizontalAction,SIGNAL(triggered()),this,SLOT(ShowMirrorHorizontal()));//实现撤销和重做的动作(ACtion)//撤销和重做
    undoAction =newQAction(QIcon(":/src/undo.png"),"撤销",this);connect(undoAction,SIGNAL(triggered()),showWidget->text,SLOT(undo()));
    redoAction =newQAction(QIcon(":/src/redo.png"),"重做",this);connect(redoAction,SIGNAL(triggered()),showWidget->text,SLOT(redo()));//在工具栏上嵌入控件//设置字号
   fontLabel1 =newQLabel(tr("字体:"));
   fontComboBox =new QFontComboBox;
   fontComboBox->setFontFilters(QFontComboBox::ScalableFonts);
   fontLabel2 =newQLabel(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(QTextCharFormat&)));/******************排版功能********************************///左对齐、右对齐、居中和两端对齐
   actGrp =newQActionGroup(this);
   leftAction =newQAction(QIcon(":/src/left.png"),"左对齐",actGrp);

   leftAction->setCheckable(true);
   rightAction =newQAction(QIcon(":/src/right.png"),"右对齐 ",actGrp);
   rightAction->setCheckable(true);
   centerAction =newQAction(QIcon(":/src/center.png")," 居中", actGrp);
   centerAction->setCheckable(true);
   justifyAction =newQAction(QIcon(":/src/justify.png"),"两端对齐 ",actGrp);
   justifyAction->setCheckable(true);connect(actGrp,SIGNAL(triggered(QAction*)),this,SLOT(ShowAlignment(QAction*)));}voidMainWindow::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);}voidMainWindow::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);

    listToolBar =addToolBar("list");
    listToolBar->addWidget(listLabel);
    listToolBar->addWidget(listComboBox);
    listToolBar->addSeparator();
    listToolBar->addActions(actGrp->actions());}voidMainWindow::ShowNewFile()//新建文件的槽{
    MainWindow *newMainWindow =new MainWindow;
    newMainWindow->show();}voidMainWindow::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);}}}#if1voidMainWindow::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#if0voidMainWindow::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();}}}#endifvoidMainWindow::ShowPrintText()//文本打印{
    QPrinter printer;
    QPrintDialog printDialog(&printer,this);if(printDialog.exec()){//获得QTextEdit对象的文档
        QTextDocument *doc =showWidget->text->document();
        doc->print(&printer);//打印}}voidMainWindow::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);}}voidMainWindow::ShowZoomIn()//图像放大{if(img.isNull())//有效性判断{return;}

    QMatrix matrix;//声明一个QMatrix类的实例
    matrix.scale(2,2);
    img = img.transformed(matrix);
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));}voidMainWindow::ShowZoomOut()//图像缩小{if(img.isNull()){return;}
    QMatrix matrix;
    matrix.scale(0.5,0.5);
    img=img.transformed(matrix);
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));}voidMainWindow::ShowRotate90()//旋转90°{if(img.isNull()){return;}
    QMatrix matrix;
    matrix.rotate(90);
    img = img.transformed(matrix);
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));}voidMainWindow::ShowRotate180()//旋转180°{if(img.isNull()){return;}
    QMatrix matrix;
    matrix.rotate(180);
    img = img.transformed(matrix);
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));}voidMainWindow::ShowRotate270()//旋转270°{if(img.isNull()){return;}
    QMatrix matrix;
    matrix.rotate(270);
    img = img.transformed(matrix);
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));}voidMainWindow::ShowMirrorVertical()//纵向镜像{if(img.isNull())return;
    img=img.mirrored(false,true);
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));}voidMainWindow::ShowMirrorHorizontal()//横向镜像{if(img.isNull())return;
    img=img.mirrored(true,false);
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));}/************************文本编辑***********************************/voidMainWindow::ShowFontComboBox(QString comboStr){
    QTextCharFormat fmt;//设置字体
    fmt.setFontFamily(comboStr);mergeFormat(fmt);}voidMainWindow::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)}voidMainWindow::ShowSizeSpinBox(QString spinValue){
    QTextCharFormat fmt;
    fmt.setFontPointSize(spinValue.toFloat());
    showWidget->text->mergeCurrentCharFormat(fmt);}voidMainWindow::ShowBoldBtn(){
    QTextCharFormat fmt;
    fmt.setFontWeight(boldBtn->isChecked()?QFont::Bold:QFont:: Normal);
    showWidget->text->mergeCurrentCharFormat(fmt);}voidMainWindow::ShowItalicBtn(){
    QTextCharFormat fmt;
    fmt.setFontItalic(italicBtn->isChecked());
    showWidget->text->mergeCurrentCharFormat(fmt);}voidMainWindow::ShowUnderlineBtn(){
    QTextCharFormat fmt;
    fmt.setFontUnderline(underlineBtn->isChecked());
    showWidget->text->mergeCurrentCharFormat(fmt);}voidMainWindow::ShowColorBtn(){
    QColor color=QColorDialog::getColor(Qt::red,this);if(color.isValid()){
        QTextCharFormat fmt;
        fmt.setForeground(color);
        showWidget->text->mergeCurrentCharFormat(fmt);}}voidMainWindow::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());}/********************排版编辑********************************/voidMainWindow::ShowAlignment(QAction *act)//当前段落对齐{if(act==leftAction)
    showWidget->text->setAlignment(Qt::AlignLeft);if(act==rightAction)
    showWidget->text->setAlignment(Qt::AlignRight);if(act==centerAction)
    showWidget->text->setAlignment(Qt::AlignCenter);if(act==justifyAction)
    showWidget->text->setAlignment(Qt::AlignJustify);}voidMainWindow::ShowCursorPositionChanged(){if(showWidget->text->alignment()==Qt::AlignLeft)
    leftAction->setChecked(true);if(showWidget->text->alignment()==Qt::AlignRight)
    rightAction->setChecked(true);if(showWidget->text->alignment()==Qt::AlignCenter)
    centerAction->setChecked(true);if(showWidget->text->alignment()==Qt::AlignJustify)
    justifyAction->setChecked(true);}voidMainWindow::ShowList(int index)//实现文本排序{///获得编辑框的 QTextCursor 对象指针
    QTextCursor cursor=showWidget->text->textCursor();if(index!=0){
        QTextListFormat::Style style=QTextListFormat:: ListDisc;switch(index){default:case1:
        style=QTextListFormat::ListDisc;break;case2:
        style=QTextListFormat::ListCircle;break;case3:
        style=QTextListFormat::ListSquare;break;case4:
        style=QTextListFormat::ListDecimal;break;case5:

        style=QTextListFormat::ListLowerAlpha;break;case6:
        style=QTextListFormat::ListUpperAlpha;break;case7:
        style=QTextListFormat::ListLowerRoman;break;case8:
        style=QTextListFormat::ListUpperRoman;break;}//设置缩进
        cursor.beginEditBlock();
        QTextBlockFormat blockFmt=cursor.blockFormat();
        QTextListFormat listFmt;if(cursor.currentList()){
            listFmt=cursor.currentList()->format();}else{
            listFmt.setIndent(blockFmt.indent()+1);
            blockFmt.setIndent(0);
            cursor.setBlockFormat(blockFmt);}

        listFmt.setStyle(style);
        cursor.createList(listFmt);
        cursor.endEditBlock();}else{
        QTextBlockFormat bfmt;
        bfmt.setObjectIndex(-1);
        cursor.mergeBlockFormat(bfmt);}}

showwidget.cpp

#include"showwidget.h"ShowWidget::ShowWidget(QWidget *parent):QWidget(parent){
    imageLabel =new QLabel;
    imageLabel->setScaledContents(true);
    text =new QTextEdit;
    QHBoxLayout *mainLayout =newQHBoxLayout(this);
    mainLayout->addWidget(imageLabel);
    mainLayout->addWidget(text);}

四、总结

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

标签: qt c++ ui

本文转载自: https://blog.csdn.net/weixin_44759598/article/details/126743609
版权归原作者 乔伊波伊 o(*^@^*)o 所有, 如有侵权,请联系我们删除。

“Qt5开发从入门到精通&mdash;&mdash;第五篇五节( 文本编辑器 Easy Word 开发 V1.4详解 )”的评论:

还没有评论