QT文本编辑器的编写
程序
图片和文档的设计
//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 = nullptr);
QImage img;
QLabel *imageLabel;
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);
text=new QTextEdit;
QHBoxLayout *mainLayout=new QHBoxLayout(this);
mainLayout->addWidget(imageLabel);
mainLayout->addWidget(text);
}
菜单栏、工具栏、快捷键的编写
//imageprocessor.h
#ifndef IMAGEPROCESSOR_H
#define IMAGEPROCESSOR_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 ImageProcessor : public QMainWindow
{
Q_OBJECT
public:
ImageProcessor(QWidget *parent = 0);
~ImageProcessor();
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 *zoonInAction;
QAction *zoonOutAction;
//旋转菜单项
QAction *rotate90Action;
QAction *rotate180Action;
QAction *rotate270Action;
//镜像菜单栏
QAction *mirrorVerticalAction;
QAction *mirrorHorizontalAction;
QAction *undoAction;
QAction *redoAction;
//工具栏
QToolBar *fileTool;
QToolBar *zoomTool;
QToolBar *rotateTool;
QToolBar *mirrorTool;
QToolBar *doToolBar;
protected slots:
void ShowNewFile();
void ShowOpenFile();
void ShowPrintText();
void ShowPrintImage();
void showzoonIn();
void showzoonOut();
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();
private:
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;
};
#endif // IMAGEPROCESSOR_H
//imageprocessor.cpp
#include "imageprocessor.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include <QPrintDialog>
#include <QPrinter>
#include <QPainter>
#include <QColorDialog>
#include <QTextList>
ImageProcessor::ImageProcessor(QWidget *parent)
: QMainWindow(parent)
{
setWindowTitle("Easy Word");
showWidget=new ShowWidget(this);
setCentralWidget(showWidget);
fontLabel1=new QLabel("字体");
fontComboBox =new QFontComboBox;
fontComboBox->setFontFilters(QFontComboBox::ScalableFonts);//过滤字体可缩放字体
fontLabel2=new QLabel("字号");
sizeComboBox=new QComboBox;
QFontDatabase db;//所有可用的字体字号本例只用到字号
foreach (int size,db.standardSizes())//返回可用的标准字号的列表
sizeComboBox->addItem(QString::number(size));
boldBtn=new QToolButton;
boldBtn->setText("bold");
boldBtn->setIcon(QIcon("bold.png"));
boldBtn->setCheckable(true);
italicBtn=new QToolButton;
italicBtn->setText("italic");
italicBtn->setIcon(QIcon("italic.png"));
italicBtn->setCheckable(true);
underlineBtn=new QToolButton;
underlineBtn->setText("underline");
underlineBtn->setIcon(QIcon("underline.png"));
underlineBtn->setCheckable(true);
colorBtn=new QToolButton;
colorBtn->setText("color");
colorBtn->setIcon(QIcon("color.png"));
colorBtn->setCheckable(true);
listLabel=new QLabel("排序");
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.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()));
}
ImageProcessor::~ImageProcessor()
{
}
void ImageProcessor::createActions()
{
//“打开”动作
openFileAction=new QAction(QIcon("open.png"),"打开",this);//设置图标、名称、父窗口
openFileAction->setShortcut(tr("Ctrl+O"));//设置此动作的组合键
openFileAction->setStatusTip("打开一个文件");//设置状态栏提示
connect(openFileAction,SIGNAL(triggered()),this,SLOT(ShowOpenFile()));
//“新建”动作
NewFileAction=new QAction(QIcon("new.png"),"新建",this);//设置图标、名称、父窗口
NewFileAction->setShortcut(tr("Ctrl+N"));//设置此动作的组合键
NewFileAction->setStatusTip("新建一个文件");//设置状态栏提示
connect(NewFileAction,SIGNAL(triggered()),this,SLOT(ShowNewFile()));
//“退出”动作
exitAction=new QAction("退出",this);//设置图标、名称、父窗口
exitAction->setShortcut(tr("Ctrl+Q"));//设置此动作的组合键
exitAction->setStatusTip("退出程序");//设置状态栏提示
connect(exitAction,SIGNAL(triggered()),this,SLOT(close()));
//“复制”动作
copyAction=new QAction(QIcon("copy.png"),"复制",this);//设置图标、名称、父窗口
copyAction->setShortcut(tr("Ctrl+C"));//设置此动作的组合键
copyAction->setStatusTip("复制文件");//设置状态栏提示
connect(copyAction,SIGNAL(triggered()),showWidget->text,SLOT(copy()));
//“剪切”动作
cutAction=new QAction(QIcon("cut.png"),"剪切",this);//设置图标、名称、父窗口
cutAction->setShortcut(tr("Ctrl+X"));//设置此动作的组合键
cutAction->setStatusTip("剪切文件");//设置状态栏提示
connect(cutAction,SIGNAL(triggered()),showWidget->text,SLOT(cut()));
//“粘贴”动作
pasteAction=new QAction(QIcon("paste.png"),"粘贴",this);//设置图标、名称、父窗口
pasteAction->setShortcut(tr("Ctrl+V"));//设置此动作的组合键
pasteAction->setStatusTip("粘贴文件");//设置状态栏提示
connect(pasteAction,SIGNAL(triggered()),showWidget->text,SLOT(paste()));
//“关于”动作
aboutAction=new QAction("关于",this);//设置图标、名称、父窗口
connect(aboutAction,SIGNAL(triggered()),this,SLOT(QMessageBox::aboutQt()));
//“打印文本”动作
PrintTextAction=new QAction("打印文本",this);
PrintTextAction->setStatusTip("打印一个文本");
connect(PrintTextAction,SIGNAL(triggered()),this,SLOT(ShowPrintText()));
//“打印文本”动作
PrintImageAction=new QAction("打印图片",this);
PrintImageAction->setStatusTip("打印一个图片");
connect(PrintImageAction,SIGNAL(triggered()),this,SLOT(ShowPrintImage()));
//“放大缩小”动作
zoonInAction=new QAction("放大",this);
zoonInAction->setStatusTip("放大图片");//设置状态栏提示
connect(zoonInAction,SIGNAL(triggered()),this,SLOT(showzoonIn()));
zoonOutAction=new QAction("缩小",this);
zoonOutAction->setStatusTip("缩小图片");//设置状态栏提示
connect(zoonOutAction,SIGNAL(triggered()),this,SLOT(showzoonOut()));
//旋转菜单项
rotate90Action=new QAction("旋转90°",this);
rotate90Action->setStatusTip("将图片旋转90°");
connect(rotate90Action,SIGNAL(triggered()),this,SLOT(ShowRotate90()));
rotate180Action=new QAction("旋转180°",this);
rotate180Action->setStatusTip("将图片旋转180°");
connect(rotate180Action,SIGNAL(triggered()),this,SLOT(ShowRotate180()));
rotate270Action=new QAction("旋转270°",this);
rotate270Action->setStatusTip("将图片旋转270°");
connect(rotate270Action,SIGNAL(triggered()),this,SLOT(ShowRotate270()));
//镜像菜单栏
mirrorVerticalAction=new QAction("纵向镜像",this);
mirrorVerticalAction->setStatusTip("对一幅图做纵向镜像");
connect(mirrorVerticalAction,SIGNAL(triggered()),this,SLOT(showMirrorVertical()));
mirrorHorizontalAction=new QAction("横向镜像",this);
mirrorHorizontalAction->setStatusTip("对一幅图做横向镜像");
connect(mirrorHorizontalAction,SIGNAL(triggered()),this,SLOT(showMirrorHorizontal()));
//撤销和重做
undoAction=new QAction("撤销",this);
redoAction=new QAction("重做",this);
actGrp=new QActionGroup(this);
leftAction=new QAction(QIcon("left.png"),"左对齐",actGrp);
leftAction->setCheckable(true);
rightAction=new QAction(QIcon("right.png"),"右对齐",actGrp);
rightAction->setCheckable(true);
centerAction=new QAction(QIcon("center.png"),"居中",actGrp);
centerAction->setCheckable(true);
justifyAction=new QAction(QIcon("justify.png"),"两端对齐",actGrp);
justifyAction->setCheckable(true);
connect(actGrp,SIGNAL(triggered(QAction*)),this,SLOT(ShowAlignment(QAction*)));
}
void ImageProcessor::createMenus()
{
//文件菜单
fileMenu=menuBar()->addMenu(tr("文件"));//调用QMainWindow的meunBar()函数即可得到主菜单栏的指针,在调用菜单栏QMenuBar的addMenu函数添加一个菜单
fileMenu->addAction(openFileAction);//在菜单里加入菜单条目
fileMenu->addAction(NewFileAction);
fileMenu->addAction(PrintTextAction);
fileMenu->addAction(PrintImageAction);
fileMenu->addSeparator();
fileMenu->addAction(exitAction);
//缩放菜单
zoomMenu=menuBar()->addMenu(tr("编辑"));//调用QMainWindow的meunBar()函数即可得到主菜单栏的指针,在调用菜单栏QMenuBar的addMenu函数添加一个菜单
zoomMenu->addAction(copyAction);//在菜单里加入菜单条目
zoomMenu->addAction(cutAction);
zoomMenu->addAction(pasteAction);
zoomMenu->addAction(aboutAction);
zoomMenu->addSeparator();
zoomMenu->addAction(zoonInAction);
zoomMenu->addAction(zoonOutAction);
//旋转菜单
rotateMenu=menuBar()->addMenu(tr("旋转"));//调用QMainWindow的meunBar()函数即可得到主窗口的菜单栏的指针,在调用菜单栏QMenuBar的addMenu函数添加一个菜单
rotateMenu->addAction(rotate90Action);//在菜单里加入菜单条目
rotateMenu->addAction(rotate180Action);
rotateMenu->addAction(rotate270Action);
//镜像菜单
mirrorMenu=menuBar()->addMenu(tr("镜像"));
mirrorMenu->addAction(mirrorVerticalAction);
mirrorMenu->addAction(mirrorHorizontalAction);
}
void ImageProcessor::createToolBars()
{
fileTool =addToolBar("File");//调用QMainWindow的addToolBar()即可获得主窗口的工具条栏
fileTool->addAction(openFileAction);
fileTool->addAction(NewFileAction);
fileTool->addAction(PrintTextAction);
fileTool->addAction(PrintImageAction);
zoomTool =addToolBar("Edit");//调用QMainWindow的addToolBar()即可获得主窗口的工具条栏
zoomTool->addAction(copyAction);
zoomTool->addAction(cutAction);
zoomTool->addAction(pasteAction);
zoomTool->addSeparator();
zoomTool->addAction(zoonInAction);
zoomTool->addAction(zoonOutAction);
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 ImageProcessor::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 ImageProcessor::mergeFormat(QTextCharFormat format)//通过光标进行格式修改
{
QTextCursor cursor =showWidget->text->textCursor();
if(!cursor.hasSelection())
cursor.select(QTextCursor::WordUnderCursor);
cursor.mergeCharFormat(format);//将得到的格式传给光标
showWidget->text->mergeCurrentCharFormat(format);//将光标的道德格式传给光标所选的字符
}
void ImageProcessor::ShowNewFile()//新建
{
ImageProcessor *newImgProcessor=new ImageProcessor;
newImgProcessor->show();
}
void ImageProcessor::ShowOpenFile()//打开文件
{
fileName=QFileDialog::getOpenFileName(this);//获得文件路径
if(!fileName.isEmpty())
{
if(showWidget->text->document()->isEmpty())
{
loadFile(fileName);
}
else
{
ImageProcessor *newImgProcessor=new ImageProcessor;
newImgProcessor->show();
newImgProcessor->loadFile(fileName);
}
}
}
void ImageProcessor::ShowPrintText()//打印
{
QPrinter *printer=new QPrinter;
QPrintDialog printDialog(printer,this);
if(printDialog.exec())
{
QTextDocument *doc=showWidget->text->document();
doc->print(printer);
}
}
void ImageProcessor::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());//设置QPainter窗口大小为图像的大小
painter.drawImage(0,0,img);//打印图像
}
}
void ImageProcessor::showzoonIn()
{
if(img.isNull())
return;
QMatrix matrix;
matrix.scale(2,2);//按照2倍比例对水平和垂直方向进行放大,并将当前现实的图形按照该坐标矩阵进行转换
img=img.transformed(matrix);
//重新设置显示图形
showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
}
void ImageProcessor::showzoonOut()
{
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 ImageProcessor::ShowRotate90()
{
if(img.isNull())
return;
QMatrix matrix;
matrix.rotate(90);
img=img.transformed(matrix);
showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
}
void ImageProcessor::ShowRotate180()
{
if(img.isNull())
return;
QMatrix matrix;
matrix.rotate(180);
img=img.transformed(matrix);
showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
}
void ImageProcessor::ShowRotate270()
{
if(img.isNull())
return;
QMatrix matrix;
matrix.rotate(270);
img=img.transformed(matrix);
showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
}
void ImageProcessor::showMirrorVertical()
{
if(img.isNull())
return;
img=img.mirrored(false,true);
showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
}
void ImageProcessor::showMirrorHorizontal()
{
if(img.isNull())
return;
img=img.mirrored(true,false);
showWidget->imageLabel->setPixmap(QPixmap::fromImage(img));
}
void ImageProcessor::ShowFontComboBox(QString comboStr)//字体
{
QTextCharFormat fmt;
fmt.setFontFamily(comboStr);
mergeFormat(fmt);
}
void ImageProcessor::ShowSizeSpinBox(QString spinValue)//字号
{
QTextCharFormat fmt;
fmt.setFontPointSize(spinValue.toFloat());//qreal在windows环境下是float型
showWidget->text->mergeCurrentCharFormat(fmt);
}
void ImageProcessor::ShowBoldBtn()//文字加粗
{
QTextCharFormat fmt;
fmt.setFontWeight(boldBtn->isChecked()?QFont::Bold:QFont::Normal);
showWidget->text->mergeCurrentCharFormat(fmt);
}
void ImageProcessor::ShowItalicBtn()//文字斜体
{
QTextCharFormat fmt;
fmt.setFontItalic(italicBtn->isChecked());
showWidget->text->mergeCurrentCharFormat(fmt);
}
void ImageProcessor::ShowUnderlineBtn()//文字下划线
{
QTextCharFormat fmt;
fmt.setFontUnderline(underlineBtn->isChecked());
showWidget->text->mergeCurrentCharFormat(fmt);
}
void ImageProcessor::ShowColorBtn()
{
QColor color=QColorDialog::getColor(Qt::red,this);
if(color.isValid())
{
QTextCharFormat fmt;
fmt.setForeground(color);
showWidget->text->mergeCurrentCharFormat(fmt);
}
}
void ImageProcessor::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 ImageProcessor::ShowList(int index)//排列方式
{
QTextCursor cursor=showWidget->text->textCursor();
if(index!=0)
{
QTextListFormat::Style style=QTextListFormat::ListDisc;
switch(index)
{
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;
}
/* 设置缩进值 */
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);
}
}
void ImageProcessor::ShowAlignment(QAction *act)//根据alignment按键状态修改文本alignment
{
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 ImageProcessor::ShowCursorPositionChanged()//根据文本内容修改alignment按键状态
{
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);
}
效果展示
工具栏很多按钮的图片并没有设置所以显示空白