第5章 Qt 5主窗口

一、Qt 5主窗口构成

QMainWindow是一个为用户提供主窗口程序的类,包含一个菜单栏(menu bar)、多个工具栏(tool bars)、多个锚接部件(dock widgets)、一个状态栏(status bar)及一个中心部件(central widget),是许多应用程序(如文本编辑器、图片编辑器等)的基础。本章将对此进行详细介绍。Qt主窗口界面布局如图5.1所示。

 1.菜单栏

菜单是一系列命令的列表。为了实现菜单、工具栏按钮、键盘快捷方式等命令的一致性,Qt使用动作(Action)来表示这些命令。Qt的菜单就是由一系列的QAction动作对象构成的列表,而菜单栏则是包容菜单的面板,它位于主窗口标题栏的下面。一个主窗口只能有一个菜单栏。

2.状态栏

状态栏通常显示GUI应用程序的一些状态信息,它位于主窗口的底部。用户可以在状态栏上添加、使用Qt窗口部件。一个主窗口只能有一个状态栏。

3.工具栏

工具栏是由一系列的类似于按钮的动作排列而成的面板,它通常由一些经常使用的命令(动作)组成。工具栏位于菜单栏的下面、状态栏的上面,可以停靠在主窗口的上、下、左、右四个方向上。一个主窗口可以包含多个工具栏。

工具条是一个可移动的窗口,它可停靠的区域由QToolBar的allowAreas决定,包括Qt::LeftToolBarArea、Qt::RightToolBarArea、Qt::TopToolBarArea、Qt::BottomToolBarArea和Qt::AllToolBarAreas。默认为Qt::AllToolBarAreas,启动后默认出现于主窗口的顶部。可通过调用setAllowAreas()函数来指定工具条可停靠的区域,例如:    

fileTool->setAllowedAreas(Qt::TopToolBarArea|Qt::LeftToolBarArea);

此函数限定文件工具条只可出现在主窗口的顶部或左侧。工具条也可通过调用setMovable()函数设定可移动性,例如:  

 fileTool->setMovable(false);

指定文件工具条不可移动,只出现于主窗口的顶部。

4.锚接部件

锚接部件作为一个容器使用,以包容其他窗口部件来实现某些功能。例如,Qt设计器的属性编辑器、对象监视器等都是由锚接部件包容其他的Qt窗口部件来实现的。它位于工具栏区的内部,可以作为一个窗口自由地浮动在主窗口上面,也可以像工具栏一样停靠在主窗口的上、下、左、右四个方向上。一个主窗口可以包含多个锚接部件。

5.中心部件

中心部件处在锚接部件区的内部、主窗口的中心。一个主窗口只能有一个中心部件。

二、综合实例---文本编辑器

(1)文件操作功能:包括新建一个文件,利用标准文件对话框QFileDialog类打开一个已存在的文件,利用QFile和QTextStream读取文件内容,打印文件(分文本打印和图像打印)。通过实例介绍标准打印对话框QPrintDialog类的使用方法,以QPrinter作为QPaintDevice画图工具实现图像打印。

(2)图像处理软件中的常用功能:包括图片的缩放、旋转、镜像等坐标变换,使用QMatrix实现图像的各种坐标变换。

(3)开发文本编辑功能:通过在工具栏上设置文字字体、字号大小、加粗、斜体、下画线及字体颜色等快捷按钮的实现,介绍在工具栏中嵌入控件的方法。其中,通过设置字体颜色功能,介绍标准颜色对话框QColorDialog类的使用方法。

(4)排版功能:通过选择某种排序方式实现对文本排序,以及实现文本对齐(包括左对齐、右对齐、居中对齐和两端对齐)和撤销、重做的方法。

 1、设计页面

2、工程组成

showwidget 主要显示文本编辑框函数所在的文件

imgprocessor 主要提供文本编辑器功能的实现,ImgProcessor类声明中的createActions()函数用于创建所有的动作、createMenus()函数用于创建菜单、createToolBars()函数用于创建工具栏;接着声明实现主窗口所需的各个元素,包括菜单、工具栏及各个动作等;最后声明用到的槽函数

 3、showwidget文件

showwidget.h

#ifndef SHOWWIDGET_H
#define SHOWWIDGET_H

#include <QWidget>
#include <QLabel>
#include <QTextEdit>
#include <QImage>
class ShowWidget : public QWidget
{
    Q_OBJECT
public:
    explicit ShowWidget(QWidget *parent = 0);
    QImage img;   //imageLabel中显示的图片
    QLabel *imageLabel;  //用来显示图片的label
    QTextEdit *text;    //文本编辑框
signals:

public slots:
};

#endif // SHOWWIDGET_H

showwidget.cpp

#include "showwidget.h"
#include <QHBoxLayout>
ShowWidget::ShowWidget(QWidget *parent) : QWidget(parent)
{
    imageLabel =new QLabel;
    imageLabel->setScaledContents(true); //图片自适应label大小
    text =new QTextEdit;
    QHBoxLayout *mainLayout =new QHBoxLayout(this);  //水平布局
    mainLayout->addWidget(imageLabel);
    mainLayout->addWidget(text);
}

4、imgprocessor文件

imgprocessor.h,声明动作、菜单、工具栏,以及文本编辑功能的槽函数

#ifndef IMGPROCESSOR_H
#define IMGPROCESSOR_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"
class ImgProcessor : public QMainWindow
{
    Q_OBJECT

public:
    ImgProcessor(QWidget *parent = 0);
    ~ImgProcessor();
    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;                          //字体工具栏
    QLabel *listLabel;                              //排序设置项
    QComboBox *listComboBox;
    QActionGroup *actGrp;
    QAction *leftAction;
    QAction *rightAction;
    QAction *centerAction;
    QAction *justifyAction;
    QToolBar *listToolBar;                          //排序工具栏
protected slots:
    void ShowNewFile();
    void ShowOpenFile();
    void ShowPrintText();
    void ShowPrintImage();
    void ShowZoomIn();
    void ShowZoomOut();
    void ShowRotate90();
    void ShowRotate180();
    void ShowRotate270();
    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);
    void ShowList(int);
    void ShowAlignment(QAction *act);
    void ShowCursorPositionChanged();
};

#endif // IMGPROCESSOR_H

imgprocessor.cpp  定义功能的具体实现

#include "imgprocessor.h"
#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include <QPrintDialog>
#include <QPrinter>
#include <QPainter>
#include <QColorDialog>
#include <QColor>
#include <QTextList>
ImgProcessor::ImgProcessor(QWidget *parent)
    : QMainWindow(parent)
{
    setWindowTitle(tr("Easy Word"));			//设置窗体标题
    showWidget =new ShowWidget(this);			//创建放置图像QLabel和文本编辑框QTextEdit的QWidget对象showWidget,并将该QWidget对象设置为中心部件。
    setCentralWidget(showWidget);
    //在工具栏上嵌入控件
    //设置字体
    fontLabel1 =new QLabel(tr("字体:"));
    fontComboBox =new QFontComboBox;
    fontComboBox->setFontFilters(QFontComboBox::ScalableFonts); //setFontFilters,过滤字体ScalableFonts显示可伸缩的字体
    fontLabel2 =new QLabel(tr("字号:"));
    sizeComboBox =new QComboBox;
    QFontDatabase db; //当前系统所有可用的格式信息,主要是字体和字号大小
    foreach(int size,db.standardSizes())   //standardSizes返回可用标准字号的列表
        sizeComboBox->addItem(QString::number(size)); //插入字号下拉列表框中
    boldBtn =new QToolButton;
    boldBtn->setIcon(QIcon(":/image/bold.png"));
    boldBtn->setCheckable(true); //此属性保持按钮是否可检查
    italicBtn =new QToolButton;
    italicBtn->setIcon(QIcon(":/image/italic.png"));
    italicBtn->setCheckable(true);
    underlineBtn =new QToolButton;
    underlineBtn->setIcon(QIcon(":/image/underline.png"));
    underlineBtn->setCheckable(true);
    colorBtn =new QToolButton;
    colorBtn->setIcon(QIcon(":/image/color.png"));
    colorBtn->setCheckable(true);
    //排序
    listLabel =new QLabel(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");
    /* 创建动作、菜单、工具栏的函数 */
    createActions();
    createMenus();
    createToolBars();
    if(img.load(":/image/image.png"))
    {
       //在imageLabel对象中放置图像
        showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
    }
    connect(fontComboBox,SIGNAL(activated(QString)),
        this,SLOT(ShowFontComboBox(QString)));
    connect(sizeComboBox,SIGNAL(activated(QString)),
        this,SLOT(ShowSizeSpinBox(QString)));
    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(showWidget->text,SIGNAL(currentCharFormatChanged(QTextCharFormat&)),this,SLOT(ShowCurrentFormatChanged(QTextCharFormat&)));

    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()));
}

void ImgProcessor::createActions()
{
    //“打开”动作
    openFileAction =new QAction(QIcon(":/image/open.png"),tr("打开"),this);//在创建“打开文件”动作的同时,指定了此动作使用的图标、名称及父窗口。
    openFileAction->setShortcut(tr("Ctrl+O"));                    //设置此动作的组合键为Ctrl+O。
    openFileAction->setStatusTip(tr("打开一个文件"));               //设定了状态栏显示,当鼠标光标移至此动作对应的菜单条目或工具栏按钮上时,在状态栏上显示“打开一个文件”的提示。
    connect(openFileAction,SIGNAL(triggered()),this,SLOT(ShowOpenFile()));
    //“新建”动作
    NewFileAction =new QAction(QIcon(":/image/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(":/image/copy.png"),tr("复制"),this);
    copyAction->setShortcut(tr("Ctrl+C"));
    copyAction->setStatusTip(tr("复制文件"));
    connect(copyAction,SIGNAL(triggered()),showWidget->text,SLOT (copy()));
    //“剪切”动作
    cutAction =new QAction(QIcon(":/image/cut.png"),tr("剪切"),this);
    cutAction->setShortcut(tr("Ctrl+X"));
    cutAction->setStatusTip(tr("剪切文件"));
    connect(cutAction,SIGNAL(triggered()),showWidget->text,SLOT (cut()));
    //“粘贴”动作
    pasteAction =new QAction(QIcon(":/image/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(":/image/printText.png"),tr("打印文本"), this);
    PrintTextAction->setStatusTip(tr("打印一个文本"));
    connect(PrintTextAction,SIGNAL(triggered()),this,SLOT(ShowPrintText()));
    //“打印图像”动作
    PrintImageAction =new QAction(QIcon(":/image/printImage.png"),tr("打印图像"), this);
    PrintImageAction->setStatusTip(tr("打印一幅图像"));
    connect(PrintImageAction,SIGNAL(triggered()),this,SLOT(ShowPrintImage()));
    //“放大”动作
    zoomInAction =new QAction(QIcon(":/image/zoomin.png"),tr("放大"),this);
    zoomInAction->setStatusTip(tr("放大一张图片"));
    connect(zoomInAction,SIGNAL(triggered()),this,SLOT(ShowZoomIn()));
    //“缩小”动作
    zoomOutAction =new QAction(QIcon(":/image/zoomout.png"),tr("缩小"),this);
    zoomOutAction->setStatusTip(tr("缩小一张图片"));
    connect(zoomOutAction,SIGNAL(triggered()),this,SLOT(ShowZoomOut()));
    //实现图像旋转的动作(Action)
    //旋转90°
    rotate90Action =new QAction(QIcon(":/image/rotate90.png"),tr("旋转90°"),this);
    rotate90Action->setStatusTip(tr("将一幅图旋转90°"));
    connect(rotate90Action,SIGNAL(triggered()),this,SLOT(ShowRotate90()));
    //旋转180°
    rotate180Action =new QAction(QIcon(":/image/rotate180.png"),tr("旋转180°"), this);
    rotate180Action->setStatusTip(tr("将一幅图旋转180°"));
    connect(rotate180Action,SIGNAL(triggered()),this,SLOT(ShowRotate180()));
    //旋转270°
    rotate270Action =new QAction(QIcon(":/image/rotate270.png"),tr("旋转270°"), this);
    rotate270Action->setStatusTip(tr("将一幅图旋转270°"));
    connect(rotate270Action,SIGNAL(triggered()),this,SLOT(ShowRotate270()));
    //实现图像镜像的动作(Action)
    //纵向镜像
    mirrorVerticalAction =new QAction(QIcon(":/image/mirrorVertical.png"), tr ("纵向镜像"),this);
    mirrorVerticalAction->setStatusTip(tr("对一幅图做纵向镜像"));
    connect(mirrorVerticalAction,SIGNAL(triggered()),this,SLOT(ShowMirrorVertical()));
    //横向镜像
    mirrorHorizontalAction =new QAction(QIcon(":/image/mirrorHorizontal.png"), tr("横向镜像"),this);
    mirrorHorizontalAction->setStatusTip(tr("对一幅图做横向镜像"));
    connect(mirrorHorizontalAction,SIGNAL(triggered()),this,SLOT(ShowMirrorHorizontal()));
    //排序:左对齐、右对齐、居中和两端对齐
    actGrp =new QActionGroup(this);
    leftAction =new QAction(QIcon(":/image/left.png"),"左对齐",actGrp);
    leftAction->setCheckable(true);
    rightAction =new QAction(QIcon(":/image/right.png"),"右对齐",actGrp);
    rightAction->setCheckable(true);
    centerAction =new QAction(QIcon(":/image/center.png"),"居中",actGrp);
    centerAction->setCheckable(true);
    justifyAction =new QAction(QIcon(":/image/justify.png"),"两端对齐",actGrp);
    justifyAction->setCheckable(true);
    connect(actGrp,SIGNAL(triggered(QAction*)),this,SLOT(ShowAlignment (QAction*)));
    //实现撤销和恢复的动作(Action)
    //撤销和恢复
    undoAction =new QAction(QIcon(":/image/undo.png"),"撤销",this);
    connect(undoAction,SIGNAL(triggered()),showWidget->text,SLOT (undo()));
    redoAction =new QAction(QIcon(":/image/redo.png"),"重做",this);
    connect(redoAction,SIGNAL(triggered()),showWidget->text,SLOT (redo()));
}

void ImgProcessor::createMenus()
{
    //文件菜单
    fileMenu =menuBar()->addMenu(tr("文件"));			//直接调用QMainWindow的menuBar()函数即可得到主窗口的菜单栏指针,再调用菜单栏QMenuBar的addMenu()函数,即可完成在菜单栏中插入一个新菜单fileMenu,fileMenu为一个QMenu类对象。
    fileMenu->addAction(openFileAction);				//调用QMenu的addAction()函数在菜单中加入菜单条目“打开”“新建”“打印文本”“打印图像”。
    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 ImgProcessor::createToolBars()
{
    //文件工具条
    fileTool =addToolBar("File");					//直接调用QMainWindow的addToolBar()函数即可获得主窗口的工具条对象,每新增一个工具条调用一次addToolBar()函数,赋予不同的名称,即可在主窗口中新增一个工具条
    fileTool->addAction(openFileAction);			//调用QToolBar的addAction()函数在工具条中插入属于本工具条的动作。类似地,实现“编辑工具条”“旋转工具条”“撤销和重做工具条”。工具条的显示可以由用户进行选择,在工具栏上单击鼠标右键将弹出工具条显示的选择菜单,用户对需要显示的工具条进行选择即可。
    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());
}

void ImgProcessor::ShowNewFile() //新建文件功能
{
    ImgProcessor *newImgProcessor =new ImgProcessor;
    newImgProcessor->show();
}

void ImgProcessor::ShowOpenFile()
{
    fileName =QFileDialog::getOpenFileName(this);
    if(!fileName.isEmpty())
    {
        if(showWidget->text->document()->isEmpty()) //检查当前中央窗体中是否已有打开的文件
        {
            loadFile(fileName);
        }
        else
        {
            ImgProcessor *newImgProcessor =new ImgProcessor;
            newImgProcessor->show();
            newImgProcessor->loadFile(fileName);
        }
    }
}

void ImgProcessor::loadFile(QString filename)  //读取文件中的内容
{
    printf("file name:%s\n",filename.data());
    QFile file(filename);
    if(file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        QTextStream textStream(&file);
        while(!textStream.atEnd())
        {
            showWidget->text->append(textStream.readLine());
            printf("read line\n");
        }
        printf("end\n");
    }
}

void ImgProcessor::ShowPrintText()
{
    QPrinter printer;							//新建一个QPrinter对象
    QPrintDialog printDialog(&printer,this);	//创建一个QPrintDialog对象,参数为QPrinter对象
    if(printDialog.exec())						//判断标准打印对话框显示后用户是否单击“打印”按钮。若单击“打印”按钮,则相关打印属性将可以通过创建QPrintDialog对象时使用的QPrinter对象获得;若用户单击“取消”按钮,则不执行后续的打印操作。
    {
       //获得QTextEdit对象的文档
        QTextDocument *doc =showWidget->text->document();
        doc->print(&printer);					//打印
    }
}

void ImgProcessor::ShowPrintImage()
{
    QPrinter printer;							//新建一个QPrinter对象
    QPrintDialog printDialog(&printer,this);	//创建一个QPrintDialog对象,参数为QPrinter对象
    if(printDialog.exec())						
    {
        QPainter painter(&printer);				//创建一个QPainter对象,并指定绘图设备为一个QPrinter对象
        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());          //设置QPainter窗口大小为图像的大小
        painter.drawImage(0,0,img);				//打印图像
    }
}

void ImgProcessor::ShowZoomIn()
{
    if(img.isNull())				//有效性判断
        return;
    QMatrix matrix;					//声明一个QMatrix类的实例
    matrix.scale(2,2);				//按照2倍比例对水平和垂直方向进行放大
    img = img.transformed(matrix); //并将当前显示的图形按照该坐标矩阵进行转换
    //重新设置显示图形
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
}

void ImgProcessor::ShowZoomOut()
{
    if(img.isNull())
        return;
    QMatrix matrix;
    matrix.scale(0.5,0.5);			//按照0.5倍比例对水平和垂直方向进行缩小 
    img = img.transformed(matrix);
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
}

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

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

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

void ImgProcessor::ShowMirrorVertical()
{
    if(img.isNull())
        return;
    img=img.mirrored(false,true); //垂直镜像
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
}

void ImgProcessor::ShowMirrorHorizontal()
{
    if(img.isNull())
        return;
    img=img.mirrored(true,false); //水平镜像
    showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
}

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

void ImgProcessor::mergeFormat(QTextCharFormat format)
{
    QTextCursor cursor =showWidget->text->textCursor();
    //获得编辑框中的光标
    if(!cursor.hasSelection())							//判断是否选择文本
        cursor.select(QTextCursor::WordUnderCursor);  //将光标所在处的词作为选区,由前后空格或“,”“.”等标点符号区分词
    cursor.mergeCharFormat(format);						//调用QTextCursor的mergeCharFormat()函数将参数format所表示的格式应用到光标所在处的字符上
    showWidget->text->mergeCurrentCharFormat(format);	//调用QTextEdit的merge CurrentCharFormat()函数将格式应用到选区内的所有字符上
}

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

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

void ImgProcessor::ShowItalicBtn()                      //设置文字显示斜体
{
    QTextCharFormat fmt;
    fmt.setFontItalic(italicBtn->isChecked());
    showWidget->text->mergeCurrentCharFormat(fmt);
}

void ImgProcessor::ShowUnderlineBtn()                   //设置文字加下画线
{
    QTextCharFormat fmt;
    fmt.setFontUnderline(underlineBtn->isChecked());
    showWidget->text->mergeCurrentCharFormat(fmt);
}

void ImgProcessor::ShowColorBtn()						//设置文字颜色
{
    QColor color=QColorDialog::getColor(Qt::red,this);	//使用颜色对话框的方式设置字体颜色
    if(color.isValid())
    {
        QTextCharFormat fmt;
            fmt.setForeground(color);
            showWidget->text->mergeCurrentCharFormat(fmt);
    }
}

void ImgProcessor::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());
}

void ImgProcessor::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);
}

void ImgProcessor::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);
}

void ImgProcessor::ShowList(int index)
{
    //获得编辑框的QTextCursor对象指针
    QTextCursor cursor=showWidget->text->textCursor();
    if(index!=0)
    {
        QTextListFormat::Style style=QTextListFormat::ListDisc;//(a)
        switch(index)                					//设置style属性值
        {
            default:
            case 1:
                style=QTextListFormat::ListDisc; break;
            case 2:
                style=QTextListFormat::ListCircle; break;
            case 3:
                style=QTextListFormat::ListSquare; break;
            case 4:
                style=QTextListFormat::ListDecimal; break;
            case 5:
                style=QTextListFormat::ListLowerAlpha; break;
            case 6:
                style=QTextListFormat::ListUpperAlpha; break;
            case 7:
                style=QTextListFormat::ListLowerRoman; break;
            case 8:
                style=QTextListFormat::ListUpperRoman; break;
        }
        /* 设置缩进值 */								//(b)
        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);
    }
}

ImgProcessor::~ImgProcessor()
{

}

5、mian文件

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

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QFont f("ZYSong18030",12);                        //设置显示的字体格式
    a.setFont(f);

    ImgProcessor w;
    w.show();

    return a.exec();
}

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值