⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 qtextedit.cpp

📁 奇趣公司比较新的qt/emd版本
💻 CPP
📖 第 1 页 / 共 5 页
字号:
/******************************************************************************** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved.**** This file is part of the QtGui 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 "qtextedit_p.h"#include "qlineedit.h"#include "qtextbrowser.h"QStringList QTextEditMimeData::formats() const{    if (!fragment.isEmpty())        return QStringList() << QString::fromLatin1("text/plain") << QString::fromLatin1("text/html");    else        return QMimeData::formats();}QVariant QTextEditMimeData::retrieveData(const QString &mimeType, QVariant::Type type) const{    if (!fragment.isEmpty())        setup();    return QMimeData::retrieveData(mimeType, type);}void QTextEditMimeData::setup() const{    QTextEditMimeData *that = const_cast<QTextEditMimeData *>(this);    that->setData(QLatin1String("text/html"), fragment.toHtml("utf-8").toUtf8());    that->setText(fragment.toPlainText());    fragment = QTextDocumentFragment();}#ifndef QT_NO_TEXTEDIT#include <qfont.h>#include <qpainter.h>#include <qevent.h>#include <qdebug.h>#include <qmime.h>#include <qdrag.h>#include <qclipboard.h>#include <qmenu.h>#include <qstyle.h>#include <qtimer.h>#include "private/qtextdocumentlayout_p.h"#include "qtextdocument.h"#include "private/qtextdocument_p.h"#include "qtextlist.h"#include "private/qtextcontrol_p.h"#include <qtextformat.h>#include <qdatetime.h>#include <qapplication.h>#include <limits.h>#include <qtexttable.h>#include <qvariant.h>#include <qinputcontext.h>class QTextEditControl : public QTextControl{public:    inline QTextEditControl(QObject *parent) : QTextControl(parent) {}    virtual QMimeData *createMimeDataFromSelection() const {        QTextEdit *ed = qobject_cast<QTextEdit *>(parent());        if (!ed)            return QTextControl::createMimeDataFromSelection();        return ed->createMimeDataFromSelection();    }    virtual bool canInsertFromMimeData(const QMimeData *source) const {        QTextEdit *ed = qobject_cast<QTextEdit *>(parent());        if (!ed)            return QTextControl::canInsertFromMimeData(source);        return ed->canInsertFromMimeData(source);    }    virtual void insertFromMimeData(const QMimeData *source) {        QTextEdit *ed = qobject_cast<QTextEdit *>(parent());        if (!ed)            QTextControl::insertFromMimeData(source);        else            ed->insertFromMimeData(source);    }};QTextEditPrivate::QTextEditPrivate()    : control(0),      autoFormatting(QTextEdit::AutoNone), tabChangesFocus(false),      lineWrap(QTextEdit::WidgetWidth), lineWrapColumnOrWidth(0),      wordWrap(QTextOption::WrapAtWordBoundaryOrAnywhere), textFormat(Qt::AutoText){    ignoreAutomaticScrollbarAdjustment = false;    preferRichText = false;    showCursorOnInitialShow = true;}void QTextEditPrivate::createAutoBulletList(){    QTextCursor cursor = control->textCursor();    cursor.beginEditBlock();    QTextBlockFormat blockFmt = cursor.blockFormat();    QTextListFormat listFmt;    listFmt.setStyle(QTextListFormat::ListDisc);    listFmt.setIndent(blockFmt.indent() + 1);    blockFmt.setIndent(0);    cursor.setBlockFormat(blockFmt);    cursor.createList(listFmt);    cursor.endEditBlock();    control->setTextCursor(cursor);}void QTextEditPrivate::init(const QString &html){    Q_Q(QTextEdit);    control = new QTextEditControl(q);    control->setPalette(q->palette());    QObject::connect(control, SIGNAL(microFocusChanged()), q, SLOT(updateMicroFocus()));    QObject::connect(control, SIGNAL(documentSizeChanged(QSizeF)), q, SLOT(_q_adjustScrollbars()));    QObject::connect(control, SIGNAL(updateRequest(QRectF)), q, SLOT(_q_repaintContents(QRectF)));    QObject::connect(control, SIGNAL(visibilityRequest(QRectF)), q, SLOT(_q_ensureVisible(QRectF)));    QObject::connect(control, SIGNAL(currentCharFormatChanged(QTextCharFormat)),                     q, SLOT(_q_currentCharFormatChanged(QTextCharFormat)));    QObject::connect(control, SIGNAL(textChanged()), q, SIGNAL(textChanged()));    QObject::connect(control, SIGNAL(undoAvailable(bool)), q, SIGNAL(undoAvailable(bool)));    QObject::connect(control, SIGNAL(redoAvailable(bool)), q, SIGNAL(redoAvailable(bool)));    QObject::connect(control, SIGNAL(copyAvailable(bool)), q, SIGNAL(copyAvailable(bool)));    QObject::connect(control, SIGNAL(selectionChanged()), q, SIGNAL(selectionChanged()));    QObject::connect(control, SIGNAL(cursorPositionChanged()), q, SIGNAL(cursorPositionChanged()));    QTextDocument *doc = control->document();    // set a null page size initially to avoid any relayouting until the textedit    // is shown. relayoutDocument() will take care of setting the page size to the    // viewport dimensions later.    doc->setPageSize(QSize(0, 0));    doc->documentLayout()->setPaintDevice(viewport);    doc->setDefaultFont(q->font());    if (!html.isEmpty())        control->setHtml(html);    hbar->setSingleStep(20);    vbar->setSingleStep(20);    viewport->setBackgroundRole(QPalette::Base);    q->setAcceptDrops(true);    q->setFocusPolicy(Qt::WheelFocus);    q->setAttribute(Qt::WA_KeyCompression);    q->setAttribute(Qt::WA_InputMethodEnabled);#ifndef QT_NO_CURSOR    viewport->setCursor(Qt::IBeamCursor);#endif}void QTextEditPrivate::_q_repaintContents(const QRectF &contentsRect){    if (!contentsRect.isValid()) {        viewport->update();        return;    }    const int xOffset = horizontalOffset();    const int yOffset = verticalOffset();    const QRectF visibleRect(xOffset, yOffset, viewport->width(), viewport->height());    QRect r = contentsRect.intersected(visibleRect).toAlignedRect();    if (r.isEmpty())        return;    r.translate(-xOffset, -yOffset);    viewport->update(r);}void QTextEditPrivate::pageUpDown(QTextCursor::MoveOperation op, QTextCursor::MoveMode moveMode){    QTextCursor cursor = control->textCursor();    bool moved = false;    qreal lastY = control->cursorRect(cursor).top();    qreal distance = 0;    // move using movePosition to keep the cursor's x    do {        qreal y = control->cursorRect(cursor).top();        distance += qAbs(y - lastY);        lastY = y;        moved = cursor.movePosition(op, moveMode);    } while (moved && distance < viewport->height());    if (moved) {        if (op == QTextCursor::Up) {            cursor.movePosition(QTextCursor::Down, moveMode);            vbar->triggerAction(QAbstractSlider::SliderPageStepSub);        } else {            cursor.movePosition(QTextCursor::Up, moveMode);            vbar->triggerAction(QAbstractSlider::SliderPageStepAdd);        }    }    control->setTextCursor(cursor);}#ifndef QT_NO_SCROLLBARstatic QSize documentSize(QTextControl *control){    QTextDocument *doc = control->document();    QAbstractTextDocumentLayout *layout = doc->documentLayout();    QSize docSize;    if (QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout)) {        docSize = tlayout->dynamicDocumentSize().toSize();        int percentageDone = tlayout->layoutStatus();        // extrapolate height        if (percentageDone > 0)            docSize.setHeight(docSize.height() * 100 / percentageDone);    } else {        docSize = layout->documentSize().toSize();    }    return docSize;}void QTextEditPrivate::_q_adjustScrollbars(){    if (ignoreAutomaticScrollbarAdjustment)        return;    ignoreAutomaticScrollbarAdjustment = true; // avoid recursion, #106108    QSize viewportSize = viewport->size();    QSize docSize = documentSize(control);    // due to the recursion guard we have to repeat this step a few times,    // as adding/removing a scroll bar will cause the document or viewport    // size to change    // ideally we should loop until the viewport size and doc size stabilize,    // but in corner cases they might fluctuate, so we need to limit the    // number of iterations    for (int i = 0; i < 4; ++i) {        hbar->setRange(0, docSize.width() - viewportSize.width());        hbar->setPageStep(viewportSize.width());        vbar->setRange(0, docSize.height() - viewportSize.height());        vbar->setPageStep(viewportSize.height());        // if we are in left-to-right mode widening the document due to        // lazy layouting does not require a repaint. If in right-to-left        // the scroll bar has the value zero and it visually has the maximum        // value (it is visually at the right), then widening the document        // keeps it at value zero but visually adjusts it to the new maximum        // on the right, hence we need an update.        if (q_func()->isRightToLeft())            viewport->update();        _q_showOrHideScrollBars();        const QSize oldViewportSize = viewportSize;        const QSize oldDocSize = docSize;        // make sure the document is layouted if the viewport width changes        viewportSize = viewport->size();        if (viewportSize.width() != oldViewportSize.width())            relayoutDocument();        docSize = documentSize(control);        if (viewportSize == oldViewportSize && docSize == oldDocSize)            break;    }    ignoreAutomaticScrollbarAdjustment = false;}#endif// rect is in content coordinatesvoid QTextEditPrivate::_q_ensureVisible(const QRectF &_rect){    const QRect rect = _rect.toRect();    if ((vbar->isVisible() && vbar->maximum() < rect.bottom())        || (hbar->isVisible() && hbar->maximum() < rect.right()))        _q_adjustScrollbars();    const int visibleWidth = viewport->width();    const int visibleHeight = viewport->height();    const bool rtl = q_func()->isRightToLeft();    if (rect.x() < horizontalOffset()) {        if (rtl)            hbar->setValue(hbar->maximum() - rect.x());        else            hbar->setValue(rect.x());    } else if (rect.x() + rect.width() > horizontalOffset() + visibleWidth) {        if (rtl)            hbar->setValue(hbar->maximum() - (rect.x() + rect.width() - visibleWidth));        else            hbar->setValue(rect.x() + rect.width() - visibleWidth);    }    if (rect.y() < verticalOffset())        vbar->setValue(rect.y());    else if (rect.y() + rect.height() > verticalOffset() + visibleHeight)        vbar->setValue(rect.y() + rect.height() - visibleHeight);}void QTextEditPrivate::ensureViewportLayouted(){    QAbstractTextDocumentLayout *layout = control->document()->documentLayout();    if (!layout)        return;    if (QTextDocumentLayout *tlayout = qobject_cast<QTextDocumentLayout *>(layout))        tlayout->ensureLayouted(verticalOffset() + viewport->height());}/*!    \class QTextEdit    \brief The QTextEdit class provides a widget that is used to edit and display    both plain and rich text.    \ingroup text    \mainclass    \tableofcontents    \section1 Introduction and Concepts    QTextEdit 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.    QTextEdit 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    signifies a paragraph. A document consists of zero or more    paragraphs. 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.    QTextEdit can display images, 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).    If you just need to display a small piece of rich text use QLabel.    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.    The shape of the mouse cursor on a QTextEdit is Qt::IBeamCursor by default.    It can be changed through the viewport()'s cursor property.    \section1 Using QTextEdit as a Display Widget    QTextEdit can display a large HTML subset, including tables and    images.    The text is set or replaced using setHtml() which deletes any    existing text and replaces it with the text passed in the    setHtml() call. If you call setHtml() with legacy HTML, and then    call toHtml(), the text that is returned may have different markup,    but will render the same. The entire text can be deleted with clear().    Text itself can be inserted using the QTextCursor class or using the    convenience functions insertHtml(), insertPlainText(), append() or    paste(). QTextCursor is also able to insert complex objects like tables    or lists into the document, and it deals with creating selections    and applying changes to selected text.    By default the text edit wraps words at whitespace to fit within    the text edit widget. The setLineWrapMode() function is used to    specify the kind of line wrap you want, or \l NoWrap if you don't    want any wrapping. Call setLineWrapMode() to set a fixed pixel width    \l FixedPixelWidth, or character column (e.g. 80 column) \l    FixedColumnWidth with the pixels or columns specified with    setLineWrapColumnOrWidth(). If you use word wrap to the widget's width    \l WidgetWidth, you can specify whether to break on whitespace or    anywhere with setWordWrapMode().    The find() function can be used to find and select a given string    within the text.    If you want to limit the total number of paragraphs in a QTextEdit,    as it is for example open useful in a log viewer, then you can use    QTextDocument's maximumBlockCount property for that.    \section2 Read-only Key Bindings    When QTextEdit is used read-only the key bindings are limited to    navigation, and text may only be selected with the mouse:    \table    \header \i Keypresses \i Action    \row \i Qt::UpArrow        \i Moves one line up.    \row \i Qt::DownArrow        \i Moves one line down.    \row \i Qt::LeftArrow        \i Moves one character to the left.    \row \i Qt::RightArrow        \i Moves one character to the right.    \row \i PageUp        \i Moves one (viewport) page up.    \row \i PageDown        \i Moves one (viewport) page down.    \row \i Home        \i Moves to the beginning of the text.    \row \i End                \i Moves to the end of the text.    \row \i Alt+Wheel         \i Scrolls the page horizontally (the Wheel is the mouse wheel).    \row \i Ctrl+Wheel        \i Zooms the text.    \row \i Ctrl+A            \i Selects all text.    \endtable    The text edit may be able to provide some meta-information. For    example, the documentTitle() function will return the text from    within HTML \c{<title>} tags.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -