📄 q3textedit.cpp
字号:
/******************************************************************************** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved.**** This file is part of the Qt3Support module of the Qt Toolkit.**** This file may be used under the terms of the GNU General Public** License version 2.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 GNU** General Public Licensing requirements will be met:** http://trolltech.com/products/qt/licenses/licensing/opensource/**** If you are unsure which license is appropriate for your use, please** review the following information:** http://trolltech.com/products/qt/licenses/licensing/licensingoverview** or contact the sales department at sales@trolltech.com.**** In addition, as a special exception, Trolltech gives you certain** additional rights. These rights are described in the Trolltech GPL** Exception version 1.0, which can be found at** http://www.trolltech.com/products/qt/gplexception/ and in the file** GPL_EXCEPTION.txt in this package.**** In addition, as a special exception, Trolltech, as the sole copyright** holder for Qt Designer, grants users of the Qt/Eclipse Integration** plug-in the right for the Qt/Eclipse Integration to link to** functionality provided by Qt Designer and its related libraries.**** Trolltech reserves all rights not expressly granted herein.**** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.******************************************************************************/#include "q3textedit.h"#ifndef QT_NO_TEXTEDIT#include <private/q3richtext_p.h>#include "qpainter.h"#include "qpen.h"#include "qbrush.h"#include "qpixmap.h"#include "qfont.h"#include "qcolor.h"#include "qstyle.h"#include "qsize.h"#include "qevent.h"#include "qtimer.h"#include "qapplication.h"#include "q3listbox.h"#include "qclipboard.h"#include "qcolordialog.h"#include "q3stylesheet.h"#include "q3dragobject.h"#include "qurl.h"#include "qcursor.h"#include "qregexp.h"#include "q3popupmenu.h"#include "qstack.h"#include "qmetaobject.h"#include "q3textbrowser.h"#include "private/q3syntaxhighlighter_p.h"#include "qtextformat.h"#ifndef QT_NO_IM#include <qinputcontext.h>#endif#ifndef QT_NO_ACCEL#include <qkeysequence.h>#define ACCEL_KEY(k) QLatin1Char('\t') + QString(QKeySequence(Qt::CTRL | Qt::Key_ ## k))#else#define ACCEL_KEY(k) QLatin1Char('\t' )+ QString(QLatin1String("Ctrl+" #k))#endif#ifdef QT_TEXTEDIT_OPTIMIZATION#define LOGOFFSET(i) d->logOffset + i#endifstruct QUndoRedoInfoPrivate{ Q3TextString text;};class Q3TextEditPrivate{public: Q3TextEditPrivate() :preeditStart(-1),preeditLength(-1),numPreeditSelections(0),ensureCursorVisibleInShowEvent(false), tabChangesFocus(false),#ifndef QT_NO_CLIPBOARD clipboard_mode(QClipboard::Clipboard),#endif#ifdef QT_TEXTEDIT_OPTIMIZATION od(0), optimMode(false), maxLogLines(-1), logOffset(0),#endif autoFormatting((uint)Q3TextEdit::AutoAll), cursorRepaintMode(false), cursorBlinkActive(false) { for (int i=0; i<7; i++) id[i] = 0; } int id[7]; int preeditStart; int preeditLength; int numPreeditSelections; uint ensureCursorVisibleInShowEvent : 1; uint tabChangesFocus : 1; QString scrollToAnchor; // used to deferr scrollToAnchor() until the show event when we are resized QString pressedName; QString onName;#ifndef QT_NO_CLIPBOARD QClipboard::Mode clipboard_mode;#endif QTimer *trippleClickTimer; QPoint trippleClickPoint;#ifdef QT_TEXTEDIT_OPTIMIZATION Q3TextEditOptimPrivate * od; bool optimMode : 1; int maxLogLines; int logOffset;#endif Q3TextEdit::AutoFormatting autoFormatting; uint cursorRepaintMode : 1; uint cursorBlinkActive : 1;};#ifndef QT_NO_MIMEclass Q3RichTextDrag : public Q3TextDrag{public: Q3RichTextDrag(QWidget *dragSource = 0, const char *name = 0); void setPlainText(const QString &txt) { setText(txt); } void setRichText(const QString &txt) { richTxt = txt; } virtual QByteArray encodedData(const char *mime) const; virtual const char* format(int i) const; static bool decode(QMimeSource *e, QString &str, const QString &mimetype, const QString &subtype); static bool canDecode(QMimeSource* e);private: QString richTxt;};Q3RichTextDrag::Q3RichTextDrag(QWidget *dragSource, const char *name) : Q3TextDrag(dragSource, name){}QByteArray Q3RichTextDrag::encodedData(const char *mime) const{ if (qstrcmp("application/x-qrichtext", mime) == 0) { return richTxt.toUtf8(); // #### perhaps we should use USC2 instead? } else return Q3TextDrag::encodedData(mime);}bool Q3RichTextDrag::decode(QMimeSource *e, QString &str, const QString &mimetype, const QString &subtype){ if (mimetype == QLatin1String("application/x-qrichtext")) { // do richtext decode const char *mime; int i; for (i = 0; (mime = e->format(i)); ++i) { if (qstrcmp("application/x-qrichtext", mime) != 0) continue; str = QString::fromUtf8(e->encodedData(mime)); return true; } return false; } // do a regular text decode QString st = subtype; return Q3TextDrag::decode(e, str, st);}bool Q3RichTextDrag::canDecode(QMimeSource* e){ if (e->provides("application/x-qrichtext")) return true; return Q3TextDrag::canDecode(e);}const char* Q3RichTextDrag::format(int i) const{ if (Q3TextDrag::format(i)) return Q3TextDrag::format(i); if (Q3TextDrag::format(i-1)) return "application/x-qrichtext"; return 0;}#endifstatic bool block_set_alignment = false;/*! \class Q3TextEdit qtextedit.h \brief The Q3TextEdit widget provides a powerful single-page rich text editor. \compat \tableofcontents \section1 Introduction and Concepts Q3TextEdit is an advanced WYSIWYG viewer/editor supporting rich text formatting using HTML-style tags. It is optimized to handle large documents and to respond quickly to user input. Q3TextEdit has four modes of operation: \table \header \i Mode \i Command \i Notes \row \i Plain Text Editor \i setTextFormat(Qt::PlainText) \i Set text with setText(); text() returns plain text. Text attributes (e.g. colors) can be set, but plain text is always returned. \row \i Rich Text Editor \i setTextFormat(Qt::RichText) \i Set text with setText(); text() returns rich text. Rich text editing is fairly limited. You can't set margins or insert images for example (although you can read and correctly display files that have margins set and that include images). This mode is mostly useful for editing small amounts of rich text. \row \i Text Viewer \i setReadOnly(true) \i Set text with setText() or append() (which has no undo history so is faster and uses less memory); text() returns plain or rich text depending on the textFormat(). This mode can correctly display a large subset of HTML tags. \row \i Log Viewer \i setTextFormat(Qt::LogText) \i Append text using append(). The widget is set to be read only and rich text support is disabled although a few HTML tags (for color, bold, italic and underline) may be used. (See \link #logtextmode Qt::LogText mode\endlink for details.) \endtable Q3TextEdit can be used as a syntax highlighting editor when used in conjunction with QSyntaxHighlighter. We recommend that you always call setTextFormat() to set the mode you want to use. If you use Qt::AutoText then setText() and append() will try to determine whether the text they are given is plain text or rich text. If you use Qt::RichText then setText() and append() will assume that the text they are given is rich text. insert() simply inserts the text it is given. Q3TextEdit works on paragraphs and characters. A paragraph is a formatted string which is word-wrapped to fit into the width of the widget. By default when reading plain text, one newline signify a paragraph. A document consists of zero or more paragraphs, indexed from 0. Characters are indexed on a per-paragraph basis, also indexed from 0. The words in the paragraph are aligned in accordance with the paragraph's alignment(). Paragraphs are separated by hard line breaks. Each character within a paragraph has its own attributes, for example, font and color. The text edit documentation uses the following concepts: \list \i \e{current format} -- this is the format at the current cursor position, \e and it is the format of the selected text if any. \i \e{current paragraph} -- the paragraph which contains the cursor. \endlist Q3TextEdit can display images (using Q3MimeSourceFactory), lists and tables. If the text is too large to view within the text edit's viewport, scroll bars will appear. The text edit can load both plain text and HTML files (a subset of HTML 3.2 and 4). The rendering style and the set of valid tags are defined by a styleSheet(). Custom tags can be created and placed in a custom style sheet. Change the style sheet with \l{setStyleSheet()}; see Q3StyleSheet for details. The images identified by image tags are displayed if they can be interpreted using the text edit's \l{Q3MimeSourceFactory}; see setMimeSourceFactory(). If you want a text browser with more navigation use QTextBrowser. If you just need to display a small piece of rich text use QLabel or QSimpleRichText. If you create a new Q3TextEdit, and want to allow the user to edit rich text, call setTextFormat(Qt::RichText) to ensure that the text is treated as rich text. (Rich text uses HTML tags to set text formatting attributes. See Q3StyleSheet for information on the HTML tags that are supported.). If you don't call setTextFormat() explicitly the text edit will guess from the text itself whether it is rich text or plain text. This means that if the text looks like HTML or XML it will probably be interpreted as rich text, so you should call setTextFormat(Qt::PlainText) to preserve such text. Note that we do not intend to add a full-featured web browser widget to Qt (because that would easily double Qt's size and only a few applications would benefit from it). The rich text support in Qt is designed to provide a fast, portable and efficient way to add reasonable online help facilities to applications, and to provide a basis for rich text editors. \section1 Using Q3TextEdit as a Display Widget Q3TextEdit can display a large HTML subset, including tables and images. The text is set or replaced using setText() which deletes any existing text and replaces it with the text passed in the setText() call. If you call setText() with legacy HTML (with setTextFormat(Qt::RichText) in force), and then call text(), the text that is returned may have different markup, but will render the same. Text can be inserted with insert(), paste(), pasteSubType() and append(). Text that is appended does not go into the undo history; this makes append() faster and consumes less memory. Text can also be cut(). The entire text is deleted with clear() and the selected text is deleted with removeSelectedText(). Selected (marked) text can also be deleted with del() (which will delete the character to the right of the cursor if no text is selected). Loading and saving text is achieved using setText() and text(), for example: \code QFile file(fileName); // Read the text from a file if (file.open(IO_ReadOnly)) { QTextStream stream(&file); textEdit->setText(stream.read()); } QFile file(fileName); // Write the text to a file if (file.open(IO_WriteOnly)) { QTextStream stream(&file); stream << textEdit->text(); textEdit->setModified(false); } \endcode By default the text edit wraps words at whitespace to fit within the text edit widget. The setWordWrap() function is used to specify the kind of word wrap you want, or \c NoWrap if you don't want any wrapping. Call setWordWrap() to set a fixed pixel width \c FixedPixelWidth, or character column (e.g. 80 column) \c FixedColumnWidth with the pixels or columns specified with setWrapColumnOrWidth(). If you use word wrap to the widget's width \c WidgetWidth, you can specify whether to break on whitespace or anywhere with setWrapPolicy(). The background color is set differently than other widgets, using setPaper(). You specify a brush style which could be a plain color or a complex pixmap. Hypertext links are automatically underlined; this can be changed with setLinkUnderline(). The tab stop width is set with setTabStopWidth(). The zoomIn() and zoomOut() functions can be used to resize the text by increasing (decreasing for zoomOut()) the point size used. Images are not affected by the zoom functions. The lines() function returns the number of lines in the text and paragraphs() returns the number of paragraphs. The number of lines within a particular paragraph is returned by linesOfParagraph(). The length of the entire text in characters is returned by length().
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -