zoukankan      html  css  js  c++  java
  • 文本编辑器

            记事本类型的应用,可以打开、编辑、保存文本文档。可以增加单词高亮和其它的一些特性。
            首先,对于这一个项目,可以说有点偷懒,因为如果要开始的毕竟是一个不小的项目,不使用浏览器的话,开发起来必然需要学习太多的东西,所以就使用了Qt中的一个小小的demo-----textedit,一个富文本的编辑器,之前曾经学习过Qt编程,但是真的没有好好了解过这一类的框架,这一次就当做是自己在学习这个小小的项目吧,如果之后再有什么想法再继续深入这个小项目~~
            这个项目的最终结果是这样子的:

            可以看出来,还是挺不错的嘛,嘿嘿,下面就来慢慢的解析它吧~
            下面是这个项目的资源文件
            mac:
            editcopy.pngeditcut.pngeditpaste.pngeditredo.pngeditundo.pngexportpdf.pngfilenew.pngfileopen.pngfileprint.pngfilesave.pngtextbold.pngtextcenter.pngtextitalic.pngtextjustify.pngtextleft.pngtextright.pngtextunder.pngzoomin.pngzoomout.png
            win:
            editcopy.pngeditcut.pngeditpaste.pngeditredo.pngeditundo.pngexportpdf.pngfilenew.pngfileopen.pngfileprint.pngfilesave.pngtextbold.pngtextcenter.pngtextitalic.pngtextjustify.pngtextleft.pngtextright.pngtextunder.pngzoomin.pngzoomout.png
            logo32.png:
            logo32.png

            看项目需要从最主要的配置文件开始看,下面首先了解一下这个小项目的配置文件:
    textedit.pro:
    1. TEMPLATE = app
    2. TARGET = textedit
    3. CONFIG += qt warn_on
    4. HEADERS = textedit.h
    5. SOURCES = textedit.cpp
    6. main.cpp
    7. RESOURCES += textedit.qrc
    8. build_all:!build_pass {
    9. CONFIG -= build_all
    10. CONFIG += release
    11. }
    12. # install
    13. target.path = $$[QT_INSTALL_DEMOS]/textedit
    14. sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.html *.doc images
    15. sources.path = $$[QT_INSTALL_DEMOS]/textedit
    16. INSTALLS += target sources
    17. symbian: include($$QT_SOURCE_TREE/demos/symbianpkgrules.pri)
    TEMPLATE = app
    A> app -建立一个应用程序的makefile。这是默认值,所以如果模板没有被指定,这个将被使用。
    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.h
    SOURCES = textedit.cpp
    main.cpp

    • HEADERS - 应用程序中的所有头文件的列表。

    • SOURCES - 应用程序中的所有源文件的列表。

      RESOURCES += textedit.qrc

      加载了资源文件textedit.qrc,也就是上面的所有东西mac,win,logo32.png还有example.html

      1. <!DOCTYPE RCC><RCC version="1.0">
      2. <qresource prefix="/">
      3. <file>images/logo32.png</file>
      4. <file>images/mac/editcopy.png</file>
      5. <file>images/mac/editcut.png</file>
      6. <file>images/mac/editpaste.png</file>
      7. <file>images/mac/editredo.png</file>
      8. <file>images/mac/editundo.png</file>
      9. <file>images/mac/exportpdf.png</file>
      10. <file>images/mac/filenew.png</file>
      11. <file>images/mac/fileopen.png</file>
      12. <file>images/mac/fileprint.png</file>
      13. <file>images/mac/filesave.png</file>
      14. <file>images/mac/textbold.png</file>
      15. <file>images/mac/textcenter.png</file>
      16. <file>images/mac/textitalic.png</file>
      17. <file>images/mac/textjustify.png</file>
      18. <file>images/mac/textleft.png</file>
      19. <file>images/mac/textright.png</file>
      20. <file>images/mac/textunder.png</file>
      21. <file>images/mac/zoomin.png</file>
      22. <file>images/mac/zoomout.png</file>
      23. <file>images/win/editcopy.png</file>
      24. <file>images/win/editcut.png</file>
      25. <file>images/win/editpaste.png</file>
      26. <file>images/win/editredo.png</file>
      27. <file>images/win/editundo.png</file>
      28. <file>images/win/exportpdf.png</file>
      29. <file>images/win/filenew.png</file>
      30. <file>images/win/fileopen.png</file>
      31. <file>images/win/fileprint.png</file>
      32. <file>images/win/filesave.png</file>
      33. <file>images/win/textbold.png</file>
      34. <file>images/win/textcenter.png</file>
      35. <file>images/win/textitalic.png</file>
      36. <file>images/win/textjustify.png</file>
      37. <file>images/win/textleft.png</file>
      38. <file>images/win/textright.png</file>
      39. <file>images/win/textunder.png</file>
      40. <file>images/win/zoomin.png</file>
      41. <file>images/win/zoomout.png</file>
      42. <file>example.html</file>
      43. </qresource>
      44. </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:

    1. #include "textedit.h"
    2. #include <QApplication>
    3. int main( int argc, char ** argv )
    4. {
    5. Q_INIT_RESOURCE(textedit);
    6. QApplication a( argc, argv );
    7. TextEdit mw;
    8. mw.resize( 700, 800 );
    9. mw.show();
    10. return a.exec();
    11. }
    首先还是包含了textedit.h文件,这个文件的主要功能是,继承了QMainWindow类,这样的话就可以生成窗口文件。初始化

    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结果。
    在对话框弹出期间,用户不可以切换同程序下的其它窗口,直到该对话框被关闭。

    这样子说起来,application总是一个模式的对话框,因为一旦生成就锁定了,但是Windows窗口不是一个模式对话框,当它生成的时候直接的就返回了应该有的数值。所以在这个应用中出现这样的情况。
    最后一句:return a.exec();
    程序进入消息循环,等待可能输入进行响应。这里main()把控制权转交给Qt,Qt完成事件处理工作,当应用程序退出的时候exec()的值就会返回。在exec()中,Qt接受并处理用户和系统的事件并且把它们传递给适当的窗口部件。

    最后来看一下,textedit文件,因为这里已经将应用程序的控制权转交给Qt的事件处理程序,这样子我们就需要搞清楚,Qt的事件循环队列现在究竟发生了什么事情。
    在textedit.h文件中当然只有一个类,这个类继承了应该继承的Window窗口,并且还注册了许多事件处理机制。但是首先还是来看一下这个函数具体的行为是什么
    1. #ifndef TEXTEDIT_H
    2. #define TEXTEDIT_H
    3. #include <QMainWindow>
    4. #include <QMap>
    5. #include <QPointer>
    6. QT_FORWARD_DECLARE_CLASS(QAction)
    7. QT_FORWARD_DECLARE_CLASS(QComboBox)
    8. QT_FORWARD_DECLARE_CLASS(QFontComboBox)
    9. QT_FORWARD_DECLARE_CLASS(QTextEdit)
    10. QT_FORWARD_DECLARE_CLASS(QTextCharFormat)
    11. QT_FORWARD_DECLARE_CLASS(QMenu)
    12. class TextEdit : public QMainWindow
    13. {
    14. Q_OBJECT
    15. public:
    16. TextEdit(QWidget *parent = 0);
    17. protected:
    18. virtual void closeEvent(QCloseEvent *e);
    19. private:
    20. void setupFileActions();
    21. void setupEditActions();
    22. void setupTextActions();
    23. bool load(const QString &f);
    24. bool maybeSave();
    25. void setCurrentFileName(const QString &fileName);
    26. private slots:
    27. void fileNew();
    28. void fileOpen();
    29. bool fileSave();
    30. bool fileSaveAs();
    31. void filePrint();
    32. void filePrintPreview();
    33. void filePrintPdf();
    34. void textBold();
    35. void textUnderline();
    36. void textItalic();
    37. void textFamily(const QString &f);
    38. void textSize(const QString &p);
    39. void textStyle(int styleIndex);
    40. void textColor();
    41. void textAlign(QAction *a);
    42. void currentCharFormatChanged(const QTextCharFormat &format);
    43. void cursorPositionChanged();
    44. void clipboardDataChanged();
    45. void about();
    46. void printPreview(QPrinter *);
    47. private:
    48. void mergeFormatOnWordOrSelection(const QTextCharFormat &format);
    49. void fontChanged(const QFont &f);
    50. void colorChanged(const QColor &c);
    51. void alignmentChanged(Qt::Alignment a);
    52. QAction *actionSave,
    53. *actionTextBold,
    54. *actionTextUnderline,
    55. *actionTextItalic,
    56. *actionTextColor,
    57. *actionAlignLeft,
    58. *actionAlignCenter,
    59. *actionAlignRight,
    60. *actionAlignJustify,
    61. *actionUndo,
    62. *actionRedo,
    63. *actionCut,
    64. *actionCopy,
    65. *actionPaste;
    66. QComboBox *comboStyle;
    67. QFontComboBox *comboFont;
    68. QComboBox *comboSize;
    69. QToolBar *tb;
    70. QString fileName;
    71. QTextEdit *textEdit;
    72. };
    73. #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)

    这写函数在网上查找说的是前置声明一样的东西,说的就像是头文件一样,但是问什么不直接的包含到头文件中去呢,这个还是后来再纠结吧。
    下面需要我们对于这个类进行分析了,总算是到了重头戏了:
    每一个窗口类中,对于Qt来说,只有在class中加入了Q_OBJECT,你才能使用QT中的signal和slot机制。
    1. /****************************************************************************
    2. **
    3. ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
    4. ** Contact: http://www.qt-project.org/legal
    5. **
    6. ** This file is part of the demonstration applications of the Qt Toolkit.
    7. **
    8. ** $QT_BEGIN_LICENSE:LGPL$
    9. ** Commercial License Usage
    10. ** Licensees holding valid commercial Qt licenses may use this file in
    11. ** accordance with the commercial license agreement provided with the
    12. ** Software or, alternatively, in accordance with the terms contained in
    13. ** a written agreement between you and Digia. For licensing terms and
    14. ** conditions see http://qt.digia.com/licensing. For further information
    15. ** use the contact form at http://qt.digia.com/contact-us.
    16. **
    17. ** GNU Lesser General Public License Usage
    18. ** Alternatively, this file may be used under the terms of the GNU Lesser
    19. ** General Public License version 2.1 as published by the Free Software
    20. ** Foundation and appearing in the file LICENSE.LGPL included in the
    21. ** packaging of this file. Please review the following information to
    22. ** ensure the GNU Lesser General Public License version 2.1 requirements
    23. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
    24. **
    25. ** In addition, as a special exception, Digia gives you certain additional
    26. ** rights. These rights are described in the Digia Qt LGPL Exception
    27. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
    28. **
    29. ** GNU General Public License Usage
    30. ** Alternatively, this file may be used under the terms of the GNU
    31. ** General Public License version 3.0 as published by the Free Software
    32. ** Foundation and appearing in the file LICENSE.GPL included in the
    33. ** packaging of this file. Please review the following information to
    34. ** ensure the GNU General Public License version 3.0 requirements will be
    35. ** met: http://www.gnu.org/copyleft/gpl.html.
    36. **
    37. **
    38. ** $QT_END_LICENSE$
    39. **
    40. ****************************************************************************/
    41. #include "textedit.h"
    42. #include <QAction>
    43. #include <QApplication>
    44. #include <QClipboard>
    45. #include <QColorDialog>
    46. #include <QComboBox>
    47. #include <QFontComboBox>
    48. #include <QFile>
    49. #include <QFileDialog>
    50. #include <QFileInfo>
    51. #include <QFontDatabase>
    52. #include <QMenu>
    53. #include <QMenuBar>
    54. #include <QPrintDialog>
    55. #include <QPrinter>
    56. #include <QTextCodec>
    57. #include <QTextEdit>
    58. #include <QToolBar>
    59. #include <QTextCursor>
    60. #include <QTextDocumentWriter>
    61. #include <QTextList>
    62. #include <QtDebug>
    63. #include <QCloseEvent>
    64. #include <QMessageBox>
    65. #include <QPrintPreviewDialog>
    66. #ifdef Q_WS_MAC
    67. const QString rsrcPath = ":/images/mac";
    68. #else
    69. const QString rsrcPath = ":/images/win";
    70. #endif
    71. TextEdit::TextEdit(QWidget *parent)
    72. : QMainWindow(parent)
    73. {
    74. setToolButtonStyle(Qt::ToolButtonFollowStyle);
    75. setupFileActions();
    76. setupEditActions();
    77. setupTextActions();
    78. {
    79. QMenu *helpMenu = new QMenu(tr("Help"), this);
    80. menuBar()->addMenu(helpMenu);
    81. helpMenu->addAction(tr("About"), this, SLOT(about()));
    82. helpMenu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt()));
    83. }
    84. textEdit = new QTextEdit(this);
    85. connect(textEdit, SIGNAL(currentCharFormatChanged(QTextCharFormat)),
    86. this, SLOT(currentCharFormatChanged(QTextCharFormat)));
    87. connect(textEdit, SIGNAL(cursorPositionChanged()),
    88. this, SLOT(cursorPositionChanged()));
    89. setCentralWidget(textEdit);
    90. textEdit->setFocus();
    91. setCurrentFileName(QString());
    92. fontChanged(textEdit->font());
    93. colorChanged(textEdit->textColor());
    94. alignmentChanged(textEdit->alignment());
    95. connect(textEdit->document(), SIGNAL(modificationChanged(bool)),
    96. actionSave, SLOT(setEnabled(bool)));
    97. connect(textEdit->document(), SIGNAL(modificationChanged(bool)),
    98. this, SLOT(setWindowModified(bool)));
    99. connect(textEdit->document(), SIGNAL(undoAvailable(bool)),
    100. actionUndo, SLOT(setEnabled(bool)));
    101. connect(textEdit->document(), SIGNAL(redoAvailable(bool)),
    102. actionRedo, SLOT(setEnabled(bool)));
    103. setWindowModified(textEdit->document()->isModified());
    104. actionSave->setEnabled(textEdit->document()->isModified());
    105. actionUndo->setEnabled(textEdit->document()->isUndoAvailable());
    106. actionRedo->setEnabled(textEdit->document()->isRedoAvailable());
    107. connect(actionUndo, SIGNAL(triggered()), textEdit, SLOT(undo()));
    108. connect(actionRedo, SIGNAL(triggered()), textEdit, SLOT(redo()));
    109. actionCut->setEnabled(false);
    110. actionCopy->setEnabled(false);
    111. connect(actionCut, SIGNAL(triggered()), textEdit, SLOT(cut()));
    112. connect(actionCopy, SIGNAL(triggered()), textEdit, SLOT(copy()));
    113. connect(actionPaste, SIGNAL(triggered()), textEdit, SLOT(paste()));
    114. connect(textEdit, SIGNAL(copyAvailable(bool)), actionCut, SLOT(setEnabled(bool)));
    115. connect(textEdit, SIGNAL(copyAvailable(bool)), actionCopy, SLOT(setEnabled(bool)));
    116. #ifndef QT_NO_CLIPBOARD
    117. connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged()));
    118. #endif
    119. QString initialFile = ":/example.html";
    120. const QStringList args = QCoreApplication::arguments();
    121. if (args.count() == 2)
    122. initialFile = args.at(1);
    123. if (!load(initialFile))
    124. fileNew();
    125. }
    126. void TextEdit::closeEvent(QCloseEvent *e)
    127. {
    128. if (maybeSave())
    129. e->accept();
    130. else
    131. e->ignore();
    132. }
    133. void TextEdit::setupFileActions()
    134. {
    135. QToolBar *tb = new QToolBar(this);
    136. tb->setWindowTitle(tr("File Actions"));
    137. addToolBar(tb);
    138. QMenu *menu = new QMenu(tr("&File"), this);
    139. menuBar()->addMenu(menu);
    140. QAction *a;
    141. QIcon newIcon = QIcon::fromTheme("document-new", QIcon(rsrcPath + "/filenew.png"));
    142. a = new QAction( newIcon, tr("&New"), this);
    143. a->setPriority(QAction::LowPriority);
    144. a->setShortcut(QKeySequence::New);
    145. connect(a, SIGNAL(triggered()), this, SLOT(fileNew()));
    146. tb->addAction(a);
    147. menu->addAction(a);
    148. a = new QAction(QIcon::fromTheme("document-open", QIcon(rsrcPath + "/fileopen.png")),
    149. tr("&Open..."), this);
    150. a->setShortcut(QKeySequence::Open);
    151. connect(a, SIGNAL(triggered()), this, SLOT(fileOpen()));
    152. tb->addAction(a);
    153. menu->addAction(a);
    154. menu->addSeparator();
    155. actionSave = a = new QAction(QIcon::fromTheme("document-save", QIcon(rsrcPath + "/filesave.png")),
    156. tr("&Save"), this);
    157. a->setShortcut(QKeySequence::Save);
    158. connect(a, SIGNAL(triggered()), this, SLOT(fileSave()));
    159. a->setEnabled(false);
    160. tb->addAction(a);
    161. menu->addAction(a);
    162. a = new QAction(tr("Save &As..."), this);
    163. a->setPriority(QAction::LowPriority);
    164. connect(a, SIGNAL(triggered()), this, SLOT(fileSaveAs()));
    165. menu->addAction(a);
    166. menu->addSeparator();
    167. #ifndef QT_NO_PRINTER
    168. a = new QAction(QIcon::fromTheme("document-print", QIcon(rsrcPath + "/fileprint.png")),
    169. tr("&Print..."), this);
    170. a->setPriority(QAction::LowPriority);
    171. a->setShortcut(QKeySequence::Print);
    172. connect(a, SIGNAL(triggered()), this, SLOT(filePrint()));
    173. tb->addAction(a);
    174. menu->addAction(a);
    175. a = new QAction(QIcon::fromTheme("fileprint", QIcon(rsrcPath + "/fileprint.png")),
    176. tr("Print Preview..."), this);
    177. connect(a, SIGNAL(triggered()), this, SLOT(filePrintPreview()));
    178. menu->addAction(a);
    179. a = new QAction(QIcon::fromTheme("exportpdf", QIcon(rsrcPath + "/exportpdf.png")),
    180. tr("&Export PDF..."), this);
    181. a->setPriority(QAction::LowPriority);
    182. a->setShortcut(Qt::CTRL + Qt::Key_D);
    183. connect(a, SIGNAL(triggered()), this, SLOT(filePrintPdf()));
    184. tb->addAction(a);
    185. menu->addAction(a);
    186. menu->addSeparator();
    187. #endif
    188. a = new QAction(tr("&Quit"), this);
    189. a->setShortcut(Qt::CTRL + Qt::Key_Q);
    190. connect(a, SIGNAL(triggered()), this, SLOT(close()));
    191. menu->addAction(a);
    192. }
    193. void TextEdit::setupEditActions()
    194. {
    195. QToolBar *tb = new QToolBar(this);
    196. tb->setWindowTitle(tr("Edit Actions"));
    197. addToolBar(tb);
    198. QMenu *menu = new QMenu(tr("&Edit"), this);
    199. menuBar()->addMenu(menu);
    200. QAction *a;
    201. a = actionUndo = new QAction(QIcon::fromTheme("edit-undo", QIcon(rsrcPath + "/editundo.png")),
    202. tr("&Undo"), this);
    203. a->setShortcut(QKeySequence::Undo);
    204. tb->addAction(a);
    205. menu->addAction(a);
    206. a = actionRedo = new QAction(QIcon::fromTheme("edit-redo", QIcon(rsrcPath + "/editredo.png")),
    207. tr("&Redo"), this);
    208. a->setPriority(QAction::LowPriority);
    209. a->setShortcut(QKeySequence::Redo);
    210. tb->addAction(a);
    211. menu->addAction(a);
    212. menu->addSeparator();
    213. a = actionCut = new QAction(QIcon::fromTheme("edit-cut", QIcon(rsrcPath + "/editcut.png")),
    214. tr("Cu&t"), this);
    215. a->setPriority(QAction::LowPriority);
    216. a->setShortcut(QKeySequence::Cut);
    217. tb->addAction(a);
    218. menu->addAction(a);
    219. a = actionCopy = new QAction(QIcon::fromTheme("edit-copy", QIcon(rsrcPath + "/editcopy.png")),
    220. tr("&Copy"), this);
    221. a->setPriority(QAction::LowPriority);
    222. a->setShortcut(QKeySequence::Copy);
    223. tb->addAction(a);
    224. menu->addAction(a);
    225. a = actionPaste = new QAction(QIcon::fromTheme("edit-paste", QIcon(rsrcPath + "/editpaste.png")),
    226. tr("&Paste"), this);
    227. a->setPriority(QAction::LowPriority);
    228. a->setShortcut(QKeySequence::Paste);
    229. tb->addAction(a);
    230. menu->addAction(a);
    231. #ifndef QT_NO_CLIPBOARD
    232. if (const QMimeData *md = QApplication::clipboard()->mimeData())
    233. actionPaste->setEnabled(md->hasText());
    234. #endif
    235. }
    236. void TextEdit::setupTextActions()
    237. {
    238. QToolBar *tb = new QToolBar(this);
    239. tb->setWindowTitle(tr("Format Actions"));
    240. addToolBar(tb);
    241. QMenu *menu = new QMenu(tr("F&ormat"), this);
    242. menuBar()->addMenu(menu);
    243. actionTextBold = new QAction(QIcon::fromTheme("format-text-bold", QIcon(rsrcPath + "/textbold.png")),
    244. tr("&Bold"), this);
    245. actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B);
    246. actionTextBold->setPriority(QAction::LowPriority);
    247. QFont bold;
    248. bold.setBold(true);
    249. actionTextBold->setFont(bold);
    250. connect(actionTextBold, SIGNAL(triggered()), this, SLOT(textBold()));
    251. tb->addAction(actionTextBold);
    252. menu->addAction(actionTextBold);
    253. actionTextBold->setCheckable(true);
    254. actionTextItalic = new QAction(QIcon::fromTheme("format-text-italic", QIcon(rsrcPath + "/textitalic.png")),
    255. tr("&Italic"), this);
    256. actionTextItalic->setPriority(QAction::LowPriority);
    257. actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I);
    258. QFont italic;
    259. italic.setItalic(true);
    260. actionTextItalic->setFont(italic);
    261. connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(textItalic()));
    262. tb->addAction(actionTextItalic);
    263. menu->addAction(actionTextItalic);
    264. actionTextItalic->setCheckable(true);
    265. actionTextUnderline = new QAction(QIcon::fromTheme("format-text-underline", QIcon(rsrcPath + "/textunder.png")),
    266. tr("&Underline"), this);
    267. actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U);
    268. actionTextUnderline->setPriority(QAction::LowPriority);
    269. QFont underline;
    270. underline.setUnderline(true);
    271. actionTextUnderline->setFont(underline);
    272. connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(textUnderline()));
    273. tb->addAction(actionTextUnderline);
    274. menu->addAction(actionTextUnderline);
    275. actionTextUnderline->setCheckable(true);
    276. menu->addSeparator();
    277. QActionGroup *grp = new QActionGroup(this);
    278. connect(grp, SIGNAL(triggered(QAction*)), this, SLOT(textAlign(QAction*)));
    279. // Make sure the alignLeft is always left of the alignRight
    280. if (QApplication::isLeftToRight()) {
    281. actionAlignLeft = new QAction(QIcon::fromTheme("format-justify-left", QIcon(rsrcPath + "/textleft.png")),
    282. tr("&Left"), grp);
    283. actionAlignCenter = new QAction(QIcon::fromTheme("format-justify-center", QIcon(rsrcPath + "/textcenter.png")), tr("C&enter"), grp);
    284. actionAlignRight = new QAction(QIcon::fromTheme("format-justify-right", QIcon(rsrcPath + "/textright.png")), tr("&Right"), grp);
    285. } else {
    286. actionAlignRight = new QAction(QIcon::fromTheme("format-justify-right", QIcon(rsrcPath + "/textright.png")), tr("&Right"), grp);
    287. actionAlignCenter = new QAction(QIcon::fromTheme("format-justify-center", QIcon(rsrcPath + "/textcenter.png")), tr("C&enter"), grp);
    288. actionAlignLeft = new QAction(QIcon::fromTheme("format-justify-left", QIcon(rsrcPath + "/textleft.png")), tr("&Left"), grp);
    289. }
    290. actionAlignJustify = new QAction(QIcon::fromTheme("format-justify-fill", QIcon(rsrcPath + "/textjustify.png")), tr("&Justify"), grp);
    291. actionAlignLeft->setShortcut(Qt::CTRL + Qt::Key_L);
    292. actionAlignLeft->setCheckable(true);
    293. actionAlignLeft->setPriority(QAction::LowPriority);
    294. actionAlignCenter->setShortcut(Qt::CTRL + Qt::Key_E);
    295. actionAlignCenter->setCheckable(true);
    296. actionAlignCenter->setPriority(QAction::LowPriority);
    297. actionAlignRight->setShortcut(Qt::CTRL + Qt::Key_R);
    298. actionAlignRight->setCheckable(true);
    299. actionAlignRight->setPriority(QAction::LowPriority);
    300. actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J);
    301. actionAlignJustify->setCheckable(true);
    302. actionAlignJustify->setPriority(QAction::LowPriority);
    303. tb->addActions(grp->actions());
    304. menu->addActions(grp->actions());
    305. menu->addSeparator();
    306. QPixmap pix(16, 16);
    307. pix.fill(Qt::black);
    308. actionTextColor = new QAction(pix, tr("&Color..."), this);
    309. connect(actionTextColor, SIGNAL(triggered()), this, SLOT(textColor()));
    310. tb->addAction(actionTextColor);
    311. menu->addAction(actionTextColor);
    312. tb = new QToolBar(this);
    313. tb->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea);
    314. tb->setWindowTitle(tr("Format Actions"));
    315. addToolBarBreak(Qt::TopToolBarArea);
    316. addToolBar(tb);
    317. comboStyle = new QComboBox(tb);
    318. tb->addWidget(comboStyle);
    319. comboStyle->addItem("Standard");
    320. comboStyle->addItem("Bullet List (Disc)");
    321. comboStyle->addItem("Bullet List (Circle)");
    322. comboStyle->addItem("Bullet List (Square)");
    323. comboStyle->addItem("Ordered List (Decimal)");
    324. comboStyle->addItem("Ordered List (Alpha lower)");
    325. comboStyle->addItem("Ordered List (Alpha upper)");
    326. comboStyle->addItem("Ordered List (Roman lower)");
    327. comboStyle->addItem("Ordered List (Roman upper)");
    328. connect(comboStyle, SIGNAL(activated(int)),
    329. this, SLOT(textStyle(int)));
    330. comboFont = new QFontComboBox(tb);
    331. tb->addWidget(comboFont);
    332. connect(comboFont, SIGNAL(activated(QString)),
    333. this, SLOT(textFamily(QString)));
    334. comboSize = new QComboBox(tb);
    335. comboSize->setObjectName("comboSize");
    336. tb->addWidget(comboSize);
    337. comboSize->setEditable(true);
    338. QFontDatabase db;
    339. foreach(int size, db.standardSizes())
    340. comboSize->addItem(QString::number(size));
    341. connect(comboSize, SIGNAL(activated(QString)),
    342. this, SLOT(textSize(QString)));
    343. comboSize->setCurrentIndex(comboSize->findText(QString::number(QApplication::font()
    344. .pointSize())));
    345. }
    346. bool TextEdit::load(const QString &f)
    347. {
    348. if (!QFile::exists(f))
    349. return false;
    350. QFile file(f);
    351. if (!file.open(QFile::ReadOnly))
    352. return false;
    353. QByteArray data = file.readAll();
    354. QTextCodec *codec = Qt::codecForHtml(data);
    355. QString str = codec->toUnicode(data);
    356. if (Qt::mightBeRichText(str)) {
    357. textEdit->setHtml(str);
    358. } else {
    359. str = QString::fromLocal8Bit(data);
    360. textEdit->setPlainText(str);
    361. }
    362. setCurrentFileName(f);
    363. return true;
    364. }
    365. bool TextEdit::maybeSave()
    366. {
    367. if (!textEdit->document()->isModified())
    368. return true;
    369. if (fileName.startsWith(QLatin1String(":/")))
    370. return true;
    371. QMessageBox::StandardButton ret;
    372. ret = QMessageBox::warning(this, tr("Application"),
    373. tr("The document has been modified. "
    374. "Do you want to save your changes?"),
    375. QMessageBox::Save | QMessageBox::Discard
    376. | QMessageBox::Cancel);
    377. if (ret == QMessageBox::Save)
    378. return fileSave();
    379. else if (ret == QMessageBox::Cancel)
    380. return false;
    381. return true;
    382. }
    383. void TextEdit::setCurrentFileName(const QString &fileName)
    384. {
    385. this->fileName = fileName;
    386. textEdit->document()->setModified(false);
    387. QString shownName;
    388. if (fileName.isEmpty())
    389. shownName = "untitled.txt";
    390. else
    391. shownName = QFileInfo(fileName).fileName();
    392. setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("Rich Text")));
    393. setWindowModified(false);
    394. }
    395. void TextEdit::fileNew()
    396. {
    397. if (maybeSave()) {
    398. textEdit->clear();
    399. setCurrentFileName(QString());
    400. }
    401. }
    402. void TextEdit::fileOpen()
    403. {
    404. QString fn = QFileDialog::getOpenFileName(this, tr("Open File..."),
    405. QString(), tr("HTML-Files (*.htm *.html);;All Files (*)"));
    406. if (!fn.isEmpty())
    407. load(fn);
    408. }
    409. bool TextEdit::fileSave()
    410. {
    411. if (fileName.isEmpty())
    412. return fileSaveAs();
    413. QTextDocumentWriter writer(fileName);
    414. bool success = writer.write(textEdit->document());
    415. if (success)
    416. textEdit->document()->setModified(false);
    417. return success;
    418. }
    419. bool TextEdit::fileSaveAs()
    420. {
    421. QString fn = QFileDialog::getSaveFileName(this, tr("Save as..."),
    422. QString(), tr("ODF files (*.odt);;HTML-Files (*.htm *.html);;All Files (*)"));
    423. if (fn.isEmpty())
    424. return false;
    425. if (! (fn.endsWith(".odt", Qt::CaseInsensitive) || fn.endsWith(".htm", Qt::CaseInsensitive) || fn.endsWith(".html", Qt::CaseInsensitive)) )
    426. fn += ".odt"; // default
    427. setCurrentFileName(fn);
    428. return fileSave();
    429. }
    430. void TextEdit::filePrint()
    431. {
    432. #ifndef QT_NO_PRINTER
    433. QPrinter printer(QPrinter::HighResolution);
    434. QPrintDialog *dlg = new QPrintDialog(&printer, this);
    435. if (textEdit->textCursor().hasSelection())
    436. dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection);
    437. dlg->setWindowTitle(tr("Print Document"));
    438. if (dlg->exec() == QDialog::Accepted) {
    439. textEdit->print(&printer);
    440. }
    441. delete dlg;
    442. #endif
    443. }
    444. void TextEdit::filePrintPreview()
    445. {
    446. #ifndef QT_NO_PRINTER
    447. QPrinter printer(QPrinter::HighResolution);
    448. QPrintPreviewDialog preview(&printer, this);
    449. connect(&preview, SIGNAL(paintRequested(QPrinter*)), SLOT(printPreview(QPrinter*)));
    450. preview.exec();
    451. #endif
    452. }
    453. void TextEdit::printPreview(QPrinter *printer)
    454. {
    455. #ifdef QT_NO_PRINTER
    456. Q_UNUSED(printer);
    457. #else
    458. textEdit->print(printer);
    459. #endif
    460. }
    461. void TextEdit::filePrintPdf()
    462. {
    463. #ifndef QT_NO_PRINTER
    464. //! [0]
    465. QString fileName = QFileDialog::getSaveFileName(this, "Export PDF",
    466. QString(), "*.pdf");
    467. if (!fileName.isEmpty()) {
    468. if (QFileInfo(fileName).suffix().isEmpty())
    469. fileName.append(".pdf");
    470. QPrinter printer(QPrinter::HighResolution);
    471. printer.setOutputFormat(QPrinter::PdfFormat);
    472. printer.setOutputFileName(fileName);
    473. textEdit->document()->print(&printer);
    474. }
    475. //! [0]
    476. #endif
    477. }
    478. void TextEdit::textBold()
    479. {
    480. QTextCharFormat fmt;
    481. fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal);
    482. mergeFormatOnWordOrSelection(fmt);
    483. }
    484. void TextEdit::textUnderline()
    485. {
    486. QTextCharFormat fmt;
    487. fmt.setFontUnderline(actionTextUnderline->isChecked());
    488. mergeFormatOnWordOrSelection(fmt);
    489. }
    490. void TextEdit::textItalic()
    491. {
    492. QTextCharFormat fmt;
    493. fmt.setFontItalic(actionTextItalic->isChecked());
    494. mergeFormatOnWordOrSelection(fmt);
    495. }
    496. void TextEdit::textFamily(const QString &f)
    497. {
    498. QTextCharFormat fmt;
    499. fmt.setFontFamily(f);
    500. mergeFormatOnWordOrSelection(fmt);
    501. }
    502. void TextEdit::textSize(const QString &p)
    503. {
    504. qreal pointSize = p.toFloat();
    505. if (p.toFloat() > 0) {
    506. QTextCharFormat fmt;
    507. fmt.setFontPointSize(pointSize);
    508. mergeFormatOnWordOrSelection(fmt);
    509. }
    510. }
    511. void TextEdit::textStyle(int styleIndex)
    512. {
    513. QTextCursor cursor = textEdit->textCursor();
    514. if (styleIndex != 0) {
    515. QTextListFormat::Style style = QTextListFormat::ListDisc;
    516. switch (styleIndex) {
    517. default:
    518. case 1:
    519. style = QTextListFormat::ListDisc;
    520. break;
    521. case 2:
    522. style = QTextListFormat::ListCircle;
    523. break;
    524. case 3:
    525. style = QTextListFormat::ListSquare;
    526. break;
    527. case 4:
    528. style = QTextListFormat::ListDecimal;
    529. break;
    530. case 5:
    531. style = QTextListFormat::ListLowerAlpha;
    532. break;
    533. case 6:
    534. style = QTextListFormat::ListUpperAlpha;
    535. break;
    536. case 7:
    537. style = QTextListFormat::ListLowerRoman;
    538. break;
    539. case 8:
    540. style = QTextListFormat::ListUpperRoman;
    541. break;
    542. }
    543. cursor.beginEditBlock();
    544. QTextBlockFormat blockFmt = cursor.blockFormat();
    545. QTextListFormat listFmt;
    546. if (cursor.currentList()) {
    547. listFmt = cursor.currentList()->format();
    548. } else {
    549. listFmt.setIndent(blockFmt.indent() + 1);
    550. blockFmt.setIndent(0);
    551. cursor.setBlockFormat(blockFmt);
    552. }
    553. listFmt.setStyle(style);
    554. cursor.createList(listFmt);
    555. cursor.endEditBlock();
    556. } else {
    557. // ####
    558. QTextBlockFormat bfmt;
    559. bfmt.setObjectIndex(-1);
    560. cursor.mergeBlockFormat(bfmt);
    561. }
    562. }
    563. void TextEdit::textColor()
    564. {
    565. QColor col = QColorDialog::getColor(textEdit->textColor(), this);
    566. if (!col.isValid())
    567. return;
    568. QTextCharFormat fmt;
    569. fmt.setForeground(col);
    570. mergeFormatOnWordOrSelection(fmt);
    571. colorChanged(col);
    572. }
    573. void TextEdit::textAlign(QAction *a)
    574. {
    575. if (a == actionAlignLeft)
    576. textEdit->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute);
    577. else if (a == actionAlignCenter)
    578. textEdit->setAlignment(Qt::AlignHCenter);
    579. else if (a == actionAlignRight)
    580. textEdit->setAlignment(Qt::AlignRight | Qt::AlignAbsolute);
    581. else if (a == actionAlignJustify)
    582. textEdit->setAlignment(Qt::AlignJustify);
    583. }
    584. void TextEdit::currentCharFormatChanged(const QTextCharFormat &format)
    585. {
    586. fontChanged(format.font());
    587. colorChanged(format.foreground().color());
    588. }
    589. void TextEdit::cursorPositionChanged()
    590. {
    591. alignmentChanged(textEdit->alignment());
    592. }
    593. void TextEdit::clipboardDataChanged()
    594. {
    595. #ifndef QT_NO_CLIPBOARD
    596. if (const QMimeData *md = QApplication::clipboard()->mimeData())
    597. actionPaste->setEnabled(md->hasText());
    598. #endif
    599. }
    600. void TextEdit::about()
    601. {
    602. QMessageBox::about(this, tr("About"), tr("This example demonstrates Qt's "
    603. "rich text editing facilities in action, providing an example "
    604. "document for you to experiment with."));
    605. }
    606. void TextEdit::mergeFormatOnWordOrSelection(const QTextCharFormat &format)
    607. {
    608. QTextCursor cursor = textEdit->textCursor();
    609. if (!cursor.hasSelection())
    610. cursor.select(QTextCursor::WordUnderCursor);
    611. cursor.mergeCharFormat(format);
    612. textEdit->mergeCurrentCharFormat(format);
    613. }
    614. void TextEdit::fontChanged(const QFont &f)
    615. {
    616. comboFont->setCurrentIndex(comboFont->findText(QFontInfo(f).family()));
    617. comboSize->setCurrentIndex(comboSize->findText(QString::number(f.pointSize())));
    618. actionTextBold->setChecked(f.bold());
    619. actionTextItalic->setChecked(f.italic());
    620. actionTextUnderline->setChecked(f.underline());
    621. }
    622. void TextEdit::colorChanged(const QColor &c)
    623. {
    624. QPixmap pix(16, 16);
    625. pix.fill(c);
    626. actionTextColor->setIcon(pix);
    627. }
    628. void TextEdit::alignmentChanged(Qt::Alignment a)
    629. {
    630. if (a & Qt::AlignLeft) {
    631. actionAlignLeft->setChecked(true);
    632. } else if (a & Qt::AlignHCenter) {
    633. actionAlignCenter->setChecked(true);
    634. } else if (a & Qt::AlignRight) {
    635. actionAlignRight->setChecked(true);
    636. } else if (a & Qt::AlignJustify) {
    637. actionAlignJustify->setChecked(true);
    638. }
    639. }
    这个函数中最重要的部分还是初始化的部分:
    1. TextEdit::TextEdit(QWidget *parent)
    2. : QMainWindow(parent)
    3. {
    4. setToolButtonStyle(Qt::ToolButtonFollowStyle);
    5. setupFileActions();
    6. setupEditActions();
    7. setupTextActions();
    8. {
    9. QMenu *helpMenu = new QMenu(tr("Help"), this);
    10. menuBar()->addMenu(helpMenu);
    11. helpMenu->addAction(tr("About"), this, SLOT(about()));
    12. helpMenu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt()));
    13. }
    14. textEdit = new QTextEdit(this);
    15. connect(textEdit, SIGNAL(currentCharFormatChanged(QTextCharFormat)),
    16. this, SLOT(currentCharFormatChanged(QTextCharFormat)));
    17. connect(textEdit, SIGNAL(cursorPositionChanged()),
    18. this, SLOT(cursorPositionChanged()));
    19. setCentralWidget(textEdit);
    20. textEdit->setFocus();
    21. setCurrentFileName(QString());
    22. fontChanged(textEdit->font());
    23. colorChanged(textEdit->textColor());
    24. alignmentChanged(textEdit->alignment());
    25. connect(textEdit->document(), SIGNAL(modificationChanged(bool)),
    26. actionSave, SLOT(setEnabled(bool)));
    27. connect(textEdit->document(), SIGNAL(modificationChanged(bool)),
    28. this, SLOT(setWindowModified(bool)));
    29. connect(textEdit->document(), SIGNAL(undoAvailable(bool)),
    30. actionUndo, SLOT(setEnabled(bool)));
    31. connect(textEdit->document(), SIGNAL(redoAvailable(bool)),
    32. actionRedo, SLOT(setEnabled(bool)));
    33. setWindowModified(textEdit->document()->isModified());
    34. actionSave->setEnabled(textEdit->document()->isModified());
    35. actionUndo->setEnabled(textEdit->document()->isUndoAvailable());
    36. actionRedo->setEnabled(textEdit->document()->isRedoAvailable());
    37. connect(actionUndo, SIGNAL(triggered()), textEdit, SLOT(undo()));
    38. connect(actionRedo, SIGNAL(triggered()), textEdit, SLOT(redo()));
    39. actionCut->setEnabled(false);
    40. actionCopy->setEnabled(false);
    41. connect(actionCut, SIGNAL(triggered()), textEdit, SLOT(cut()));
    42. connect(actionCopy, SIGNAL(triggered()), textEdit, SLOT(copy()));
    43. connect(actionPaste, SIGNAL(triggered()), textEdit, SLOT(paste()));
    44. connect(textEdit, SIGNAL(copyAvailable(bool)), actionCut, SLOT(setEnabled(bool)));
    45. connect(textEdit, SIGNAL(copyAvailable(bool)), actionCopy, SLOT(setEnabled(bool)));
    46. #ifndef QT_NO_CLIPBOARD
    47. connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged()));
    48. #endif
    49. QString initialFile = ":/example.html";
    50. const QStringList args = QCoreApplication::arguments();
    51. if (args.count() == 2)
    52. initialFile = args.at(1);
    53. if (!load(initialFile))
    54. fileNew();
    55. }
    这里首先调用几个函数进行初始化,进行行为的连接,之后进行信号与槽机制的完善,对于每一个事件进行了各种有用的操作。最后生成了该文件。当然,这里的知识点在于,对于这些信号机制的深入了解现在现在的水平还不够,但是在初始化中进行各种行为的组成明显的可以的。这样,这个任务就算是基本结束了吧~~~













  • 相关阅读:
    vue与自定义元素的关系
    vue用组件构建应用
    vue处理用户输入
    vue条件与循环
    vue声明式渲染
    Java编程的逻辑 (86)
    Java编程的逻辑 (85)
    Java编程的逻辑 (84)
    Java编程的逻辑 (83)
    Java编程的逻辑 (82)
  • 原文地址:https://www.cnblogs.com/clifff/p/5044676.html
Copyright © 2011-2022 走看看