文本编辑器








































TEMPLATE = appTARGET = texteditCONFIG += qt warn_onHEADERS = textedit.hSOURCES = textedit.cpp \main.cppRESOURCES += textedit.qrcbuild_all:!build_pass {CONFIG -= build_allCONFIG += release}# installtarget.path = $$[QT_INSTALL_DEMOS]/texteditsources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.html *.doc imagessources.path = $$[QT_INSTALL_DEMOS]/texteditINSTALLS += target sourcessymbian: include($$QT_SOURCE_TREE/demos/symbianpkgrules.pri)
B> lib - 建立一个库的makefile。
C> vcapp - 建立一个应用程序的VisualStudio项目文件。
D> vclib - 建立一个库的VisualStudio项目文件。
E> subdirs -这是一个特殊的模板,它可以创建一个能够进入特定目录并且为一个项目文件生成makefile并且为它调用make的makefile。
“app”模板告诉qmake为建立一个应用程序生成一个makefile。当使用这个模板时,下面这些qmake系统变量是被承认的。你应该在你的.pro文件中使用它们来为你的应用程序指定特定信息。
TARGET = textedit
这一句表示了应用程序的名称
CONFIG += qt warn_on
CONFIG用来告诉qmake关于应用程序的配置信息。
CONFIG+= qt warn_on release
在这里使用“+=”,是因为我们添加我们的配置选项到任何一个已经存在中。这样做比使用“=”那样替换已经指定的所有选项是更安全的。
A> qt部分告诉qmake这个应用程序是使用Qt来连编的。这也就是说qmake在连接和为编译添加所需的包含路径的时候会考虑到Qt库的。
B> warn_on部分告诉qmake要把编译器设置为输出警告信息的。
C> release部分告诉qmake应用程序必须被连编为一个发布的应用程序。在开发过程中,程序员也可以使用debug来替换releas
HEADERS = textedit.hSOURCES = textedit.cpp \ main.cppHEADERS - 应用程序中的所有头文件的列表。
SOURCES - 应用程序中的所有源文件的列表。
RESOURCES += textedit.qrc
加载了资源文件textedit.qrc,也就是上面的所有东西mac,win,logo32.png还有example.html
<!DOCTYPE RCC><RCC version="1.0"><qresource prefix="/"><file>images/logo32.png</file><file>images/mac/editcopy.png</file><file>images/mac/editcut.png</file><file>images/mac/editpaste.png</file><file>images/mac/editredo.png</file><file>images/mac/editundo.png</file><file>images/mac/exportpdf.png</file><file>images/mac/filenew.png</file><file>images/mac/fileopen.png</file><file>images/mac/fileprint.png</file><file>images/mac/filesave.png</file><file>images/mac/textbold.png</file><file>images/mac/textcenter.png</file><file>images/mac/textitalic.png</file><file>images/mac/textjustify.png</file><file>images/mac/textleft.png</file><file>images/mac/textright.png</file><file>images/mac/textunder.png</file><file>images/mac/zoomin.png</file><file>images/mac/zoomout.png</file><file>images/win/editcopy.png</file><file>images/win/editcut.png</file><file>images/win/editpaste.png</file><file>images/win/editredo.png</file><file>images/win/editundo.png</file><file>images/win/exportpdf.png</file><file>images/win/filenew.png</file><file>images/win/fileopen.png</file><file>images/win/fileprint.png</file><file>images/win/filesave.png</file><file>images/win/textbold.png</file><file>images/win/textcenter.png</file><file>images/win/textitalic.png</file><file>images/win/textjustify.png</file><file>images/win/textleft.png</file><file>images/win/textright.png</file><file>images/win/textunder.png</file><file>images/win/zoomin.png</file><file>images/win/zoomout.png</file><file>example.html</file></qresource></RCC>
FORMS - 应用程序中的所有.ui文件(由Qt设计器生成)的列表。
LEXSOURCES - 应用程序中的所有lex源文件的列表。
YACCSOURCES - 应用程序中的所有yacc源文件的列表。
TARGET - 可执行应用程序的名称。默认值为项目文件的名称。(如果需要扩展名,会被自动加上。)
DESTDIR - 放置可执行程序目标的目录。
DEFINES - 应用程序所需的额外的预处理程序定义的列表。
INCLUDEPATH - 应用程序所需的额外的包含路径的列表。
DEPENDPATH - 应用程序所依赖的搜索路径。
VPATH - 寻找补充文件的搜索路径。
DEF_FILE - 只有Windows需要:应用程序所要连接的.def文件。
RC_FILE - 只有Windows需要:应用程序的资源文件。
RES_FILE - 只有Windows需要:应用程序所要连接的资源文件。
你只需要使用那些你已经有值的系统变量,例如,如果你不需要任何额外的INCLUDEPATH,那么你就不需要指定它,qmake会为所需的提供默认值。例如,一个实例项目文件也许就像这样:
TEMPLATE = app
DESTDIR = c:\helloapp
HEADERS += hello.h
SOURCES += hello.cpp
SOURCES += main.cpp
DEFINES += QT_DLL
CONFIG += qt warn_on release
如果条目是单值的,比如template或者目的目录,我们是用“=”,但如果是多值条目,我们使用“+=”来为这个类型添加现有的条目。使用“=”会用新值替换原有的值,例如,如果我们写了DEFINES=QT_DLL,其它所有的定义都将被删除。
target.path = $$[QT_INSTALL_DEMOS]/textedit
sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.html *.doc images
sources.path = $$[QT_INSTALL_DEMOS]/textedit
INSTALLS += target sources
目录文件路径,将所有的文件添加进来,包括所需要的资源文件,这样子我们就已经配置好了资源文件,下面我们需要做的就是如何利用这些资源文件建立我们的项目。首先这里还是列出来我们现在有的资源文件。
各种图片资源,主要是在image目录下面。我们需要的*.html文件,在目录文件下面。下面我们需要来观察一下我们的目录文件下面有的各种*.cpp文件。
main.cpp,textedit.cpp,textedit.h,textedit.qrc(资源文件)
main.cpp:
- #include "textedit.h"
#include <QApplication>int main( int argc, char ** argv ){Q_INIT_RESOURCE(textedit);QApplication a( argc, argv );TextEdit mw;mw.resize( 700, 800 );mw.show();return a.exec();}
Q_INIT_RESOURCE(textedit);
初始化资源文件(textedit.qrc)
下面的一句话是这样子解说的:
Initializes the window system and constructs an application object with argc command line arguments in argv.
初始化窗口系统和结构化一个有着 argc, argv参数的应用
生成一个textedit类。设置大小。show()函数
show():
显示一个非模式对话框。控制权即刻返回给调用函数。
弹出窗口是否模式对话框,取决于modal属性的值。
exec():
显示一个模式对话框,并且锁住程序直到用户关闭该对话框为止。函数返回一个DialogCode结果。
在对话框弹出期间,用户不可以切换同程序下的其它窗口,直到该对话框被关闭。
- #ifndef TEXTEDIT_H
#define TEXTEDIT_H#include <QMainWindow>#include <QMap>#include <QPointer>QT_FORWARD_DECLARE_CLASS(QAction)QT_FORWARD_DECLARE_CLASS(QComboBox)QT_FORWARD_DECLARE_CLASS(QFontComboBox)QT_FORWARD_DECLARE_CLASS(QTextEdit)QT_FORWARD_DECLARE_CLASS(QTextCharFormat)QT_FORWARD_DECLARE_CLASS(QMenu)class TextEdit : public QMainWindow{Q_OBJECTpublic:TextEdit(QWidget *parent = 0);protected:virtual void closeEvent(QCloseEvent *e);private:void setupFileActions();void setupEditActions();void setupTextActions();bool load(const QString &f);bool maybeSave();void setCurrentFileName(const QString &fileName);private slots:void fileNew();void fileOpen();bool fileSave();bool fileSaveAs();void filePrint();void filePrintPreview();void filePrintPdf();void textBold();void textUnderline();void textItalic();void textFamily(const QString &f);void textSize(const QString &p);void textStyle(int styleIndex);void textColor();void textAlign(QAction *a);void currentCharFormatChanged(const QTextCharFormat &format);void cursorPositionChanged();void clipboardDataChanged();void about();void printPreview(QPrinter *);private:void mergeFormatOnWordOrSelection(const QTextCharFormat &format);void fontChanged(const QFont &f);void colorChanged(const QColor &c);void alignmentChanged(Qt::Alignment a);QAction *actionSave,*actionTextBold,*actionTextUnderline,*actionTextItalic,*actionTextColor,*actionAlignLeft,*actionAlignCenter,*actionAlignRight,*actionAlignJustify,*actionUndo,*actionRedo,*actionCut,*actionCopy,*actionPaste;QComboBox *comboStyle;QFontComboBox *comboFont;QComboBox *comboSize;QToolBar *tb;QString fileName;QTextEdit *textEdit;};#endif
#ifndef TEXTEDIT_H
#define TEXTEDIT_H
如果没有包含textedit_h,就包含这个文件,总之就是不让这个文件重复定义。#include <QMainWindow>
#include <QMap>
#include <QPointer>
这个部分包含了需要继承的QMainWindow类,还有QMap集合类,还有QPointer指针
QT_FORWARD_DECLARE_CLASS(QAction)
QT_FORWARD_DECLARE_CLASS(QComboBox)QT_FORWARD_DECLARE_CLASS(QFontComboBox)QT_FORWARD_DECLARE_CLASS(QTextEdit)QT_FORWARD_DECLARE_CLASS(QTextCharFormat)QT_FORWARD_DECLARE_CLASS(QMenu)
/******************************************************************************** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).** Contact: http://www.qt-project.org/legal**** This file is part of the demonstration applications of the Qt Toolkit.**** $QT_BEGIN_LICENSE:LGPL$** Commercial License Usage** Licensees holding valid commercial Qt licenses may use this file in** accordance with the commercial license agreement provided with the** Software or, alternatively, in accordance with the terms contained in** a written agreement between you and Digia. For licensing terms and** conditions see http://qt.digia.com/licensing. For further information** use the contact form at http://qt.digia.com/contact-us.**** GNU Lesser General Public License Usage** Alternatively, this file may be used under the terms of the GNU Lesser** General Public License version 2.1 as published by the Free Software** Foundation and appearing in the file LICENSE.LGPL included in the** packaging of this file. Please review the following information to** ensure the GNU Lesser General Public License version 2.1 requirements** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.**** In addition, as a special exception, Digia gives you certain additional** rights. These rights are described in the Digia Qt LGPL Exception** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.**** GNU General Public License Usage** Alternatively, this file may be used under the terms of the GNU** General Public License version 3.0 as published by the Free Software** Foundation and appearing in the file LICENSE.GPL included in the** packaging of this file. Please review the following information to** ensure the GNU General Public License version 3.0 requirements will be** met: http://www.gnu.org/copyleft/gpl.html.****** $QT_END_LICENSE$******************************************************************************/#include "textedit.h"#include <QAction>#include <QApplication>#include <QClipboard>#include <QColorDialog>#include <QComboBox>#include <QFontComboBox>#include <QFile>#include <QFileDialog>#include <QFileInfo>#include <QFontDatabase>#include <QMenu>#include <QMenuBar>#include <QPrintDialog>#include <QPrinter>#include <QTextCodec>#include <QTextEdit>#include <QToolBar>#include <QTextCursor>#include <QTextDocumentWriter>#include <QTextList>#include <QtDebug>#include <QCloseEvent>#include <QMessageBox>#include <QPrintPreviewDialog>#ifdef Q_WS_MACconst QString rsrcPath = ":/images/mac";#elseconst QString rsrcPath = ":/images/win";#endifTextEdit::TextEdit(QWidget *parent): QMainWindow(parent){setToolButtonStyle(Qt::ToolButtonFollowStyle);setupFileActions();setupEditActions();setupTextActions();{QMenu *helpMenu = new QMenu(tr("Help"), this);menuBar()->addMenu(helpMenu);helpMenu->addAction(tr("About"), this, SLOT(about()));helpMenu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt()));}textEdit = new QTextEdit(this);connect(textEdit, SIGNAL(currentCharFormatChanged(QTextCharFormat)),this, SLOT(currentCharFormatChanged(QTextCharFormat)));connect(textEdit, SIGNAL(cursorPositionChanged()),this, SLOT(cursorPositionChanged()));setCentralWidget(textEdit);textEdit->setFocus();setCurrentFileName(QString());fontChanged(textEdit->font());colorChanged(textEdit->textColor());alignmentChanged(textEdit->alignment());connect(textEdit->document(), SIGNAL(modificationChanged(bool)),actionSave, SLOT(setEnabled(bool)));connect(textEdit->document(), SIGNAL(modificationChanged(bool)),this, SLOT(setWindowModified(bool)));connect(textEdit->document(), SIGNAL(undoAvailable(bool)),actionUndo, SLOT(setEnabled(bool)));connect(textEdit->document(), SIGNAL(redoAvailable(bool)),actionRedo, SLOT(setEnabled(bool)));setWindowModified(textEdit->document()->isModified());actionSave->setEnabled(textEdit->document()->isModified());actionUndo->setEnabled(textEdit->document()->isUndoAvailable());actionRedo->setEnabled(textEdit->document()->isRedoAvailable());connect(actionUndo, SIGNAL(triggered()), textEdit, SLOT(undo()));connect(actionRedo, SIGNAL(triggered()), textEdit, SLOT(redo()));actionCut->setEnabled(false);actionCopy->setEnabled(false);connect(actionCut, SIGNAL(triggered()), textEdit, SLOT(cut()));connect(actionCopy, SIGNAL(triggered()), textEdit, SLOT(copy()));connect(actionPaste, SIGNAL(triggered()), textEdit, SLOT(paste()));connect(textEdit, SIGNAL(copyAvailable(bool)), actionCut, SLOT(setEnabled(bool)));connect(textEdit, SIGNAL(copyAvailable(bool)), actionCopy, SLOT(setEnabled(bool)));#ifndef QT_NO_CLIPBOARDconnect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged()));#endifQString initialFile = ":/example.html";const QStringList args = QCoreApplication::arguments();if (args.count() == 2)initialFile = args.at(1);if (!load(initialFile))fileNew();}void TextEdit::closeEvent(QCloseEvent *e){if (maybeSave())e->accept();elsee->ignore();}void TextEdit::setupFileActions(){QToolBar *tb = new QToolBar(this);tb->setWindowTitle(tr("File Actions"));addToolBar(tb);QMenu *menu = new QMenu(tr("&File"), this);menuBar()->addMenu(menu);QAction *a;QIcon newIcon = QIcon::fromTheme("document-new", QIcon(rsrcPath + "/filenew.png"));a = new QAction( newIcon, tr("&New"), this);a->setPriority(QAction::LowPriority);a->setShortcut(QKeySequence::New);connect(a, SIGNAL(triggered()), this, SLOT(fileNew()));tb->addAction(a);menu->addAction(a);a = new QAction(QIcon::fromTheme("document-open", QIcon(rsrcPath + "/fileopen.png")),tr("&Open..."), this);a->setShortcut(QKeySequence::Open);connect(a, SIGNAL(triggered()), this, SLOT(fileOpen()));tb->addAction(a);menu->addAction(a);menu->addSeparator();actionSave = a = new QAction(QIcon::fromTheme("document-save", QIcon(rsrcPath + "/filesave.png")),tr("&Save"), this);a->setShortcut(QKeySequence::Save);connect(a, SIGNAL(triggered()), this, SLOT(fileSave()));a->setEnabled(false);tb->addAction(a);menu->addAction(a);a = new QAction(tr("Save &As..."), this);a->setPriority(QAction::LowPriority);connect(a, SIGNAL(triggered()), this, SLOT(fileSaveAs()));menu->addAction(a);menu->addSeparator();#ifndef QT_NO_PRINTERa = new QAction(QIcon::fromTheme("document-print", QIcon(rsrcPath + "/fileprint.png")),tr("&Print..."), this);a->setPriority(QAction::LowPriority);a->setShortcut(QKeySequence::Print);connect(a, SIGNAL(triggered()), this, SLOT(filePrint()));tb->addAction(a);menu->addAction(a);a = new QAction(QIcon::fromTheme("fileprint", QIcon(rsrcPath + "/fileprint.png")),tr("Print Preview..."), this);connect(a, SIGNAL(triggered()), this, SLOT(filePrintPreview()));menu->addAction(a);a = new QAction(QIcon::fromTheme("exportpdf", QIcon(rsrcPath + "/exportpdf.png")),tr("&Export PDF..."), this);a->setPriority(QAction::LowPriority);a->setShortcut(Qt::CTRL + Qt::Key_D);connect(a, SIGNAL(triggered()), this, SLOT(filePrintPdf()));tb->addAction(a);menu->addAction(a);menu->addSeparator();#endifa = new QAction(tr("&Quit"), this);a->setShortcut(Qt::CTRL + Qt::Key_Q);connect(a, SIGNAL(triggered()), this, SLOT(close()));menu->addAction(a);}void TextEdit::setupEditActions(){QToolBar *tb = new QToolBar(this);tb->setWindowTitle(tr("Edit Actions"));addToolBar(tb);QMenu *menu = new QMenu(tr("&Edit"), this);menuBar()->addMenu(menu);QAction *a;a = actionUndo = new QAction(QIcon::fromTheme("edit-undo", QIcon(rsrcPath + "/editundo.png")),tr("&Undo"), this);a->setShortcut(QKeySequence::Undo);tb->addAction(a);menu->addAction(a);a = actionRedo = new QAction(QIcon::fromTheme("edit-redo", QIcon(rsrcPath + "/editredo.png")),tr("&Redo"), this);a->setPriority(QAction::LowPriority);a->setShortcut(QKeySequence::Redo);tb->addAction(a);menu->addAction(a);menu->addSeparator();a = actionCut = new QAction(QIcon::fromTheme("edit-cut", QIcon(rsrcPath + "/editcut.png")),tr("Cu&t"), this);a->setPriority(QAction::LowPriority);a->setShortcut(QKeySequence::Cut);tb->addAction(a);menu->addAction(a);a = actionCopy = new QAction(QIcon::fromTheme("edit-copy", QIcon(rsrcPath + "/editcopy.png")),tr("&Copy"), this);a->setPriority(QAction::LowPriority);a->setShortcut(QKeySequence::Copy);tb->addAction(a);menu->addAction(a);a = actionPaste = new QAction(QIcon::fromTheme("edit-paste", QIcon(rsrcPath + "/editpaste.png")),tr("&Paste"), this);a->setPriority(QAction::LowPriority);a->setShortcut(QKeySequence::Paste);tb->addAction(a);menu->addAction(a);#ifndef QT_NO_CLIPBOARDif (const QMimeData *md = QApplication::clipboard()->mimeData())actionPaste->setEnabled(md->hasText());#endif}void TextEdit::setupTextActions(){QToolBar *tb = new QToolBar(this);tb->setWindowTitle(tr("Format Actions"));addToolBar(tb);QMenu *menu = new QMenu(tr("F&ormat"), this);menuBar()->addMenu(menu);actionTextBold = new QAction(QIcon::fromTheme("format-text-bold", QIcon(rsrcPath + "/textbold.png")),tr("&Bold"), this);actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B);actionTextBold->setPriority(QAction::LowPriority);QFont bold;bold.setBold(true);actionTextBold->setFont(bold);connect(actionTextBold, SIGNAL(triggered()), this, SLOT(textBold()));tb->addAction(actionTextBold);menu->addAction(actionTextBold);actionTextBold->setCheckable(true);actionTextItalic = new QAction(QIcon::fromTheme("format-text-italic", QIcon(rsrcPath + "/textitalic.png")),tr("&Italic"), this);actionTextItalic->setPriority(QAction::LowPriority);actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I);QFont italic;italic.setItalic(true);actionTextItalic->setFont(italic);connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(textItalic()));tb->addAction(actionTextItalic);menu->addAction(actionTextItalic);actionTextItalic->setCheckable(true);actionTextUnderline = new QAction(QIcon::fromTheme("format-text-underline", QIcon(rsrcPath + "/textunder.png")),tr("&Underline"), this);actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U);actionTextUnderline->setPriority(QAction::LowPriority);QFont underline;underline.setUnderline(true);actionTextUnderline->setFont(underline);connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(textUnderline()));tb->addAction(actionTextUnderline);menu->addAction(actionTextUnderline);actionTextUnderline->setCheckable(true);menu->addSeparator();QActionGroup *grp = new QActionGroup(this);connect(grp, SIGNAL(triggered(QAction*)), this, SLOT(textAlign(QAction*)));// Make sure the alignLeft is always left of the alignRightif (QApplication::isLeftToRight()) {actionAlignLeft = new QAction(QIcon::fromTheme("format-justify-left", QIcon(rsrcPath + "/textleft.png")),tr("&Left"), grp);actionAlignCenter = new QAction(QIcon::fromTheme("format-justify-center", QIcon(rsrcPath + "/textcenter.png")), tr("C&enter"), grp);actionAlignRight = new QAction(QIcon::fromTheme("format-justify-right", QIcon(rsrcPath + "/textright.png")), tr("&Right"), grp);} else {actionAlignRight = new QAction(QIcon::fromTheme("format-justify-right", QIcon(rsrcPath + "/textright.png")), tr("&Right"), grp);actionAlignCenter = new QAction(QIcon::fromTheme("format-justify-center", QIcon(rsrcPath + "/textcenter.png")), tr("C&enter"), grp);actionAlignLeft = new QAction(QIcon::fromTheme("format-justify-left", QIcon(rsrcPath + "/textleft.png")), tr("&Left"), grp);}actionAlignJustify = new QAction(QIcon::fromTheme("format-justify-fill", QIcon(rsrcPath + "/textjustify.png")), tr("&Justify"), grp);actionAlignLeft->setShortcut(Qt::CTRL + Qt::Key_L);actionAlignLeft->setCheckable(true);actionAlignLeft->setPriority(QAction::LowPriority);actionAlignCenter->setShortcut(Qt::CTRL + Qt::Key_E);actionAlignCenter->setCheckable(true);actionAlignCenter->setPriority(QAction::LowPriority);actionAlignRight->setShortcut(Qt::CTRL + Qt::Key_R);actionAlignRight->setCheckable(true);actionAlignRight->setPriority(QAction::LowPriority);actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J);actionAlignJustify->setCheckable(true);actionAlignJustify->setPriority(QAction::LowPriority);tb->addActions(grp->actions());menu->addActions(grp->actions());menu->addSeparator();QPixmap pix(16, 16);pix.fill(Qt::black);actionTextColor = new QAction(pix, tr("&Color..."), this);connect(actionTextColor, SIGNAL(triggered()), this, SLOT(textColor()));tb->addAction(actionTextColor);menu->addAction(actionTextColor);tb = new QToolBar(this);tb->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea);tb->setWindowTitle(tr("Format Actions"));addToolBarBreak(Qt::TopToolBarArea);addToolBar(tb);comboStyle = new QComboBox(tb);tb->addWidget(comboStyle);comboStyle->addItem("Standard");comboStyle->addItem("Bullet List (Disc)");comboStyle->addItem("Bullet List (Circle)");comboStyle->addItem("Bullet List (Square)");comboStyle->addItem("Ordered List (Decimal)");comboStyle->addItem("Ordered List (Alpha lower)");comboStyle->addItem("Ordered List (Alpha upper)");comboStyle->addItem("Ordered List (Roman lower)");comboStyle->addItem("Ordered List (Roman upper)");connect(comboStyle, SIGNAL(activated(int)),this, SLOT(textStyle(int)));comboFont = new QFontComboBox(tb);tb->addWidget(comboFont);connect(comboFont, SIGNAL(activated(QString)),this, SLOT(textFamily(QString)));comboSize = new QComboBox(tb);comboSize->setObjectName("comboSize");tb->addWidget(comboSize);comboSize->setEditable(true);QFontDatabase db;foreach(int size, db.standardSizes())comboSize->addItem(QString::number(size));connect(comboSize, SIGNAL(activated(QString)),this, SLOT(textSize(QString)));comboSize->setCurrentIndex(comboSize->findText(QString::number(QApplication::font().pointSize())));}bool TextEdit::load(const QString &f){if (!QFile::exists(f))return false;QFile file(f);if (!file.open(QFile::ReadOnly))return false;QByteArray data = file.readAll();QTextCodec *codec = Qt::codecForHtml(data);QString str = codec->toUnicode(data);if (Qt::mightBeRichText(str)) {textEdit->setHtml(str);} else {str = QString::fromLocal8Bit(data);textEdit->setPlainText(str);}setCurrentFileName(f);return true;}bool TextEdit::maybeSave(){if (!textEdit->document()->isModified())return true;if (fileName.startsWith(QLatin1String(":/")))return true;QMessageBox::StandardButton ret;ret = QMessageBox::warning(this, tr("Application"),tr("The document has been modified.\n""Do you want to save your changes?"),QMessageBox::Save | QMessageBox::Discard| QMessageBox::Cancel);if (ret == QMessageBox::Save)return fileSave();else if (ret == QMessageBox::Cancel)return false;return true;}void TextEdit::setCurrentFileName(const QString &fileName){this->fileName = fileName;textEdit->document()->setModified(false);QString shownName;if (fileName.isEmpty())shownName = "untitled.txt";elseshownName = QFileInfo(fileName).fileName();setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("Rich Text")));setWindowModified(false);}void TextEdit::fileNew(){if (maybeSave()) {textEdit->clear();setCurrentFileName(QString());}}void TextEdit::fileOpen(){QString fn = QFileDialog::getOpenFileName(this, tr("Open File..."),QString(), tr("HTML-Files (*.htm *.html);;All Files (*)"));if (!fn.isEmpty())load(fn);}bool TextEdit::fileSave(){if (fileName.isEmpty())return fileSaveAs();QTextDocumentWriter writer(fileName);bool success = writer.write(textEdit->document());if (success)textEdit->document()->setModified(false);return success;}bool TextEdit::fileSaveAs(){QString fn = QFileDialog::getSaveFileName(this, tr("Save as..."),QString(), tr("ODF files (*.odt);;HTML-Files (*.htm *.html);;All Files (*)"));if (fn.isEmpty())return false;if (! (fn.endsWith(".odt", Qt::CaseInsensitive) || fn.endsWith(".htm", Qt::CaseInsensitive) || fn.endsWith(".html", Qt::CaseInsensitive)) )fn += ".odt"; // defaultsetCurrentFileName(fn);return fileSave();}void TextEdit::filePrint(){#ifndef QT_NO_PRINTERQPrinter printer(QPrinter::HighResolution);QPrintDialog *dlg = new QPrintDialog(&printer, this);if (textEdit->textCursor().hasSelection())dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection);dlg->setWindowTitle(tr("Print Document"));if (dlg->exec() == QDialog::Accepted) {textEdit->print(&printer);}delete dlg;#endif}void TextEdit::filePrintPreview(){#ifndef QT_NO_PRINTERQPrinter printer(QPrinter::HighResolution);QPrintPreviewDialog preview(&printer, this);connect(&preview, SIGNAL(paintRequested(QPrinter*)), SLOT(printPreview(QPrinter*)));preview.exec();#endif}void TextEdit::printPreview(QPrinter *printer){#ifdef QT_NO_PRINTERQ_UNUSED(printer);#elsetextEdit->print(printer);#endif}void TextEdit::filePrintPdf(){#ifndef QT_NO_PRINTER//! [0]QString fileName = QFileDialog::getSaveFileName(this, "Export PDF",QString(), "*.pdf");if (!fileName.isEmpty()) {if (QFileInfo(fileName).suffix().isEmpty())fileName.append(".pdf");QPrinter printer(QPrinter::HighResolution);printer.setOutputFormat(QPrinter::PdfFormat);printer.setOutputFileName(fileName);textEdit->document()->print(&printer);}//! [0]#endif}void TextEdit::textBold(){QTextCharFormat fmt;fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal);mergeFormatOnWordOrSelection(fmt);}void TextEdit::textUnderline(){QTextCharFormat fmt;fmt.setFontUnderline(actionTextUnderline->isChecked());mergeFormatOnWordOrSelection(fmt);}void TextEdit::textItalic(){QTextCharFormat fmt;fmt.setFontItalic(actionTextItalic->isChecked());mergeFormatOnWordOrSelection(fmt);}void TextEdit::textFamily(const QString &f){QTextCharFormat fmt;fmt.setFontFamily(f);mergeFormatOnWordOrSelection(fmt);}void TextEdit::textSize(const QString &p){qreal pointSize = p.toFloat();if (p.toFloat() > 0) {QTextCharFormat fmt;fmt.setFontPointSize(pointSize);mergeFormatOnWordOrSelection(fmt);}}void TextEdit::textStyle(int styleIndex){QTextCursor cursor = textEdit->textCursor();if (styleIndex != 0) {QTextListFormat::Style style = QTextListFormat::ListDisc;switch (styleIndex) {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 TextEdit::textColor(){QColor col = QColorDialog::getColor(textEdit->textColor(), this);if (!col.isValid())return;QTextCharFormat fmt;fmt.setForeground(col);mergeFormatOnWordOrSelection(fmt);colorChanged(col);}void TextEdit::textAlign(QAction *a){if (a == actionAlignLeft)textEdit->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute);else if (a == actionAlignCenter)textEdit->setAlignment(Qt::AlignHCenter);else if (a == actionAlignRight)textEdit->setAlignment(Qt::AlignRight | Qt::AlignAbsolute);else if (a == actionAlignJustify)textEdit->setAlignment(Qt::AlignJustify);}void TextEdit::currentCharFormatChanged(const QTextCharFormat &format){fontChanged(format.font());colorChanged(format.foreground().color());}void TextEdit::cursorPositionChanged(){alignmentChanged(textEdit->alignment());}void TextEdit::clipboardDataChanged(){#ifndef QT_NO_CLIPBOARDif (const QMimeData *md = QApplication::clipboard()->mimeData())actionPaste->setEnabled(md->hasText());#endif}void TextEdit::about(){QMessageBox::about(this, tr("About"), tr("This example demonstrates Qt's ""rich text editing facilities in action, providing an example ""document for you to experiment with."));}void TextEdit::mergeFormatOnWordOrSelection(const QTextCharFormat &format){QTextCursor cursor = textEdit->textCursor();if (!cursor.hasSelection())cursor.select(QTextCursor::WordUnderCursor);cursor.mergeCharFormat(format);textEdit->mergeCurrentCharFormat(format);}void TextEdit::fontChanged(const QFont &f){comboFont->setCurrentIndex(comboFont->findText(QFontInfo(f).family()));comboSize->setCurrentIndex(comboSize->findText(QString::number(f.pointSize())));actionTextBold->setChecked(f.bold());actionTextItalic->setChecked(f.italic());actionTextUnderline->setChecked(f.underline());}void TextEdit::colorChanged(const QColor &c){QPixmap pix(16, 16);pix.fill(c);actionTextColor->setIcon(pix);}void TextEdit::alignmentChanged(Qt::Alignment a){if (a & Qt::AlignLeft) {actionAlignLeft->setChecked(true);} else if (a & Qt::AlignHCenter) {actionAlignCenter->setChecked(true);} else if (a & Qt::AlignRight) {actionAlignRight->setChecked(true);} else if (a & Qt::AlignJustify) {actionAlignJustify->setChecked(true);}}
TextEdit::TextEdit(QWidget *parent): QMainWindow(parent){setToolButtonStyle(Qt::ToolButtonFollowStyle);setupFileActions();setupEditActions();setupTextActions();{QMenu *helpMenu = new QMenu(tr("Help"), this);menuBar()->addMenu(helpMenu);helpMenu->addAction(tr("About"), this, SLOT(about()));helpMenu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt()));}textEdit = new QTextEdit(this);connect(textEdit, SIGNAL(currentCharFormatChanged(QTextCharFormat)),this, SLOT(currentCharFormatChanged(QTextCharFormat)));connect(textEdit, SIGNAL(cursorPositionChanged()),this, SLOT(cursorPositionChanged()));setCentralWidget(textEdit);textEdit->setFocus();setCurrentFileName(QString());fontChanged(textEdit->font());colorChanged(textEdit->textColor());alignmentChanged(textEdit->alignment());connect(textEdit->document(), SIGNAL(modificationChanged(bool)),actionSave, SLOT(setEnabled(bool)));connect(textEdit->document(), SIGNAL(modificationChanged(bool)),this, SLOT(setWindowModified(bool)));connect(textEdit->document(), SIGNAL(undoAvailable(bool)),actionUndo, SLOT(setEnabled(bool)));connect(textEdit->document(), SIGNAL(redoAvailable(bool)),actionRedo, SLOT(setEnabled(bool)));setWindowModified(textEdit->document()->isModified());actionSave->setEnabled(textEdit->document()->isModified());actionUndo->setEnabled(textEdit->document()->isUndoAvailable());actionRedo->setEnabled(textEdit->document()->isRedoAvailable());connect(actionUndo, SIGNAL(triggered()), textEdit, SLOT(undo()));connect(actionRedo, SIGNAL(triggered()), textEdit, SLOT(redo()));actionCut->setEnabled(false);actionCopy->setEnabled(false);connect(actionCut, SIGNAL(triggered()), textEdit, SLOT(cut()));connect(actionCopy, SIGNAL(triggered()), textEdit, SLOT(copy()));connect(actionPaste, SIGNAL(triggered()), textEdit, SLOT(paste()));connect(textEdit, SIGNAL(copyAvailable(bool)), actionCut, SLOT(setEnabled(bool)));connect(textEdit, SIGNAL(copyAvailable(bool)), actionCopy, SLOT(setEnabled(bool)));#ifndef QT_NO_CLIPBOARDconnect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged()));#endifQString initialFile = ":/example.html";const QStringList args = QCoreApplication::arguments();if (args.count() == 2)initialFile = args.at(1);if (!load(initialFile))fileNew();}
附件列表
- editcopy.png
- editcopy_2.png
- editcut.png
- editcut_2.png
- editpaste.png
- editpaste_2.png
- editredo.png
- editredo_2.png
- editundo.png
- editundo_2.png
- exportpdf.png
- exportpdf_2.png
- filenew.png
- filenew_2.png
- fileopen.png
- fileopen_2.png
- fileprint.png
- fileprint_2.png
- filesave.png
- filesave_2.png
- logo32.png
- textbold.png
- textbold_2.png
- textcenter.png
- textcenter_2.png
- textitalic.png
- textitalic_2.png
- textjustify.png
- textjustify_2.png
- textleft.png
- textleft_2.png
- textright.png
- textright_2.png
- textunder.png
- textunder_2.png
- zoomin.png
- zoomin_2.png
- zoomout.png
- zoomout_2.png

浙公网安备 33010602011771号