/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt scene graph research project. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** 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, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qxtextedit_p.h" #include "qxtextedit_p_p.h" #include #include #include #include #include #include #include #include #include #include QT_BEGIN_NAMESPACE /*! \qmlclass TextEdit QxTextEdit \since 4.7 \brief The TextEdit item allows you to add editable formatted text to a scene. \inherits Item It can display both plain and rich text. For example: \qml TextEdit { id: edit text: "Hello World!" focus: true font.family: "Helvetica" font.pointSize: 20 color: "blue" width: 240 } \endqml \image declarative-textedit.gif Note that the TextEdit does not implement scrolling, following the cursor, or other behaviors specific to a look-and-feel. For example, to add flickable scrolling that follows the cursor: \snippet snippets/declarative/texteditor.qml 0 A particular look-and-feel might use smooth scrolling (eg. using SmoothedFollow), might have a visible scrollbar, or a scrollbar that fades in to show location, etc. Clipboard support is provided by the cut(), copy(), and paste() functions, and the selection can be handled in a traditional "mouse" mechanism by setting selectByMouse, or handled completely from QML by manipulating selectionStart and selectionEnd, or using selectAll() or selectWord(). You can translate between cursor positions (characters from the start of the document) and pixel points using positionAt() and positionToRectangle(). \sa Text */ /*! \internal \class QxTextEdit \qmlclass TextEdit \brief The QxTextEdit class provides an editable formatted text item that you can add to a QxView. It can display both plain and rich text. \image declarative-textedit.png A QxTextEdit object can be instantiated in Qml using the tag \c <TextEdit>. */ /*! Constructs a new QxTextEdit. */ QxTextEdit::QxTextEdit(QxItem *parent) : QxPaintItem(*(new QxTextEditPrivate), parent) { Q_D(QxTextEdit); d->init(); } QString QxTextEdit::text() const { Q_D(const QxTextEdit); #ifndef QT_NO_TEXTHTMLPARSER if (d->richText) return d->document->toHtml(); else #endif return d->document->toPlainText(); } /*! \qmlproperty string TextEdit::font.family Sets the family name of the font. The family name is case insensitive and may optionally include a foundry name, e.g. "Helvetica [Cronyx]". If the family is available from more than one foundry and the foundry isn't specified, an arbitrary foundry is chosen. If the family isn't available a family will be set using the font matching algorithm. */ /*! \qmlproperty bool TextEdit::font.bold Sets whether the font weight is bold. */ /*! \qmlproperty enumeration TextEdit::font.weight Sets the font's weight. The weight can be one of: \list \o Font.Light \o Font.Normal - the default \o Font.DemiBold \o Font.Bold \o Font.Black \endlist \qml TextEdit { text: "Hello"; font.weight: Font.DemiBold } \endqml */ /*! \qmlproperty bool TextEdit::font.italic Sets whether the font has an italic style. */ /*! \qmlproperty bool TextEdit::font.underline Sets whether the text is underlined. */ /*! \qmlproperty bool TextEdit::font.outline Sets whether the font has an outline style. */ /*! \qmlproperty bool TextEdit::font.strikeout Sets whether the font has a strikeout style. */ /*! \qmlproperty real TextEdit::font.pointSize Sets the font size in points. The point size must be greater than zero. */ /*! \qmlproperty int TextEdit::font.pixelSize Sets the font size in pixels. Using this function makes the font device dependent. Use \c pointSize to set the size of the font in a device independent manner. */ /*! \qmlproperty real TextEdit::font.letterSpacing Sets the letter spacing for the font. Letter spacing changes the default spacing between individual letters in the font. A value of 100 will keep the spacing unchanged; a value of 200 will enlarge the spacing after a character by the width of the character itself. */ /*! \qmlproperty real TextEdit::font.wordSpacing Sets the word spacing for the font. Word spacing changes the default spacing between individual words. A positive value increases the word spacing by a corresponding amount of pixels, while a negative value decreases the inter-word spacing accordingly. */ /*! \qmlproperty enumeration TextEdit::font.capitalization Sets the capitalization for the text. \list \o Font.MixedCase - This is the normal text rendering option where no capitalization change is applied. \o Font.AllUppercase - This alters the text to be rendered in all uppercase type. \o Font.AllLowercase - This alters the text to be rendered in all lowercase type. \o Font.SmallCaps - This alters the text to be rendered in small-caps type. \o Font.Capitalize - This alters the text to be rendered with the first character of each word as an uppercase character. \endlist \qml TextEdit { text: "Hello"; font.capitalization: Font.AllLowercase } \endqml */ /*! \qmlproperty string TextEdit::text The text to display. If the text format is AutoText the text edit will automatically determine whether the text should be treated as rich text. This determination is made using Qt::mightBeRichText(). */ void QxTextEdit::setText(const QString &text) { Q_D(QxTextEdit); if (QxTextEdit::text() == text) return; d->richText = d->format == RichText || (d->format == AutoText && Qt::mightBeRichText(text)); if (d->richText) { #ifndef QT_NO_TEXTHTMLPARSER d->control->setHtml(text); #else d->control->setPlainText(text); #endif } else { d->control->setPlainText(text); } q_textChanged(); } /*! \qmlproperty enumeration TextEdit::textFormat The way the text property should be displayed. \list \o TextEdit.AutoText \o TextEdit.PlainText \o TextEdit.RichText \o TextEdit.StyledText \endlist The default is TextEdit.AutoText. If the text format is TextEdit.AutoText the text edit will automatically determine whether the text should be treated as rich text. This determination is made using Qt::mightBeRichText(). \table \row \o \qml Column { TextEdit { font.pointSize: 24 text: "Hello World!" } TextEdit { font.pointSize: 24 textFormat: TextEdit.RichText text: "Hello World!" } TextEdit { font.pointSize: 24 textFormat: TextEdit.PlainText text: "Hello World!" } } \endqml \o \image declarative-textformat.png \endtable */ QxTextEdit::TextFormat QxTextEdit::textFormat() const { Q_D(const QxTextEdit); return d->format; } void QxTextEdit::setTextFormat(TextFormat format) { Q_D(QxTextEdit); if (format == d->format) return; bool wasRich = d->richText; d->richText = format == RichText || (format == AutoText && Qt::mightBeRichText(d->text)); if (wasRich && !d->richText) { d->control->setPlainText(d->text); updateSize(); } else if (!wasRich && d->richText) { #ifndef QT_NO_TEXTHTMLPARSER d->control->setHtml(d->text); #else d->control->setPlainText(d->text); #endif updateSize(); } d->format = format; emit textFormatChanged(d->format); } QFont QxTextEdit::font() const { Q_D(const QxTextEdit); return d->font; } void QxTextEdit::setFont(const QFont &font) { Q_D(QxTextEdit); d->font = font; d->document->setDefaultFont(d->font); if(d->cursor){ d->cursor->setHeight(QFontMetrics(d->font).height()); moveCursorDelegate(); } updateSize(); update(); } /*! \qmlproperty color TextEdit::color The text color. \qml // green text using hexadecimal notation TextEdit { color: "#00FF00"; ... } // steelblue text using SVG color name TextEdit { color: "steelblue"; ... } \endqml */ QColor QxTextEdit::color() const { Q_D(const QxTextEdit); return d->color; } void QxTextEdit::setColor(const QColor &color) { Q_D(QxTextEdit); if (d->color == color) return; d->color = color; QPalette pal = d->control->palette(); pal.setColor(QPalette::Text, color); d->control->setPalette(pal); update(); emit colorChanged(d->color); } /*! \qmlproperty color TextEdit::selectionColor The text highlight color, used behind selections. */ QColor QxTextEdit::selectionColor() const { Q_D(const QxTextEdit); return d->selectionColor; } void QxTextEdit::setSelectionColor(const QColor &color) { Q_D(QxTextEdit); if (d->selectionColor == color) return; d->selectionColor = color; QPalette pal = d->control->palette(); pal.setColor(QPalette::Highlight, color); d->control->setPalette(pal); update(); emit selectionColorChanged(d->selectionColor); } /*! \qmlproperty color TextEdit::selectedTextColor The selected text color, used in selections. */ QColor QxTextEdit::selectedTextColor() const { Q_D(const QxTextEdit); return d->selectedTextColor; } void QxTextEdit::setSelectedTextColor(const QColor &color) { Q_D(QxTextEdit); if (d->selectedTextColor == color) return; d->selectedTextColor = color; QPalette pal = d->control->palette(); pal.setColor(QPalette::HighlightedText, color); d->control->setPalette(pal); update(); emit selectedTextColorChanged(d->selectedTextColor); } /*! \qmlproperty enumeration TextEdit::horizontalAlignment \qmlproperty enumeration TextEdit::verticalAlignment Sets the horizontal and vertical alignment of the text within the TextEdit items width and height. By default, the text is top-left aligned. The valid values for \c horizontalAlignment are \c TextEdit.AlignLeft, \c TextEdit.AlignRight and \c TextEdit.AlignHCenter. The valid values for \c verticalAlignment are \c TextEdit.AlignTop, \c TextEdit.AlignBottom and \c TextEdit.AlignVCenter. */ QxTextEdit::HAlignment QxTextEdit::hAlign() const { Q_D(const QxTextEdit); return d->hAlign; } void QxTextEdit::setHAlign(QxTextEdit::HAlignment alignment) { Q_D(QxTextEdit); if (alignment == d->hAlign) return; d->hAlign = alignment; d->updateDefaultTextOption(); updateSize(); emit horizontalAlignmentChanged(d->hAlign); } QxTextEdit::VAlignment QxTextEdit::vAlign() const { Q_D(const QxTextEdit); return d->vAlign; } void QxTextEdit::setVAlign(QxTextEdit::VAlignment alignment) { Q_D(QxTextEdit); if (alignment == d->vAlign) return; d->vAlign = alignment; d->updateDefaultTextOption(); updateSize(); emit verticalAlignmentChanged(d->vAlign); } /*! \qmlproperty enumeration TextEdit::wrapMode Set this property to wrap the text to the TextEdit item's width. The text will only wrap if an explicit width has been set. \list \o TextEdit.NoWrap - no wrapping will be performed. If the text contains insufficient newlines, then implicitWidth will exceed a set width. \o TextEdit.WordWrap - wrapping is done on word boundaries only. If a word is too long, implicitWidth will exceed a set width. \o TextEdit.WrapAnywhere - wrapping is done at any point on a line, even if it occurs in the middle of a word. \o TextEdit.Wrap - if possible, wrapping occurs at a word boundary; otherwise it will occur at the appropriate point on the line, even in the middle of a word. \endlist The default is TextEdit.NoWrap. If you set a width, consider using TextEdit.Wrap. */ QxTextEdit::WrapMode QxTextEdit::wrapMode() const { Q_D(const QxTextEdit); return d->wrapMode; } void QxTextEdit::setWrapMode(WrapMode mode) { Q_D(QxTextEdit); if (mode == d->wrapMode) return; d->wrapMode = mode; d->updateDefaultTextOption(); updateSize(); emit wrapModeChanged(); } /*! \qmlproperty real TextEdit::paintedWidth Returns the width of the text, including width past the width which is covered due to insufficient wrapping if WrapMode is set. */ qreal QxTextEdit::paintedWidth() const { return implicitWidth(); } /*! \qmlproperty real TextEdit::paintedHeight Returns the height of the text, including height past the height which is covered due to there being more text than fits in the set height. */ qreal QxTextEdit::paintedHeight() const { return implicitHeight(); } /*! \qmlmethod rectangle TextEdit::positionToRectangle(position) Returns the rectangle at the given \a position in the text. The x, y, and height properties correspond to the cursor that would describe that position. */ QRectF QxTextEdit::positionToRectangle(int pos) const { Q_D(const QxTextEdit); QTextCursor c(d->document); c.setPosition(pos); return d->control->cursorRect(c); } /*! \qmlmethod int TextEdit::positionAt(x,y) Returns the text position closest to pixel position (\a x,\a y). Position 0 is before the first character, position 1 is after the first character but before the second, and so on until position text.length, which is after all characters. */ int QxTextEdit::positionAt(int x, int y) const { Q_D(const QxTextEdit); int r = d->document->documentLayout()->hitTest(QPoint(x,y-d->yoff), Qt::FuzzyHit); return r; } /*! \qmlmethod int TextEdit::moveCursorSelection(int pos) Moves the cursor to \a position and updates the selection accordingly. (To only move the cursor, set the \l cursorPosition property.) When this method is called it additionally sets either the selectionStart or the selectionEnd (whichever was at the previous cursor position) to the specified position. This allows you to easily extend and contract the selected text range. For example, take this sequence of calls: \code cursorPosition = 5 moveCursorSelection(9) moveCursorSelection(7) \endcode This moves the cursor to position 5, extend the selection end from 5 to 9 and then retract the selection end from 9 to 7, leaving the text from position 5 to 7 selected (the 6th and 7th characters). */ void QxTextEdit::moveCursorSelection(int pos) { //Note that this is the same as setCursorPosition but with the KeepAnchor flag set Q_D(QxTextEdit); QTextCursor cursor = d->control->textCursor(); if (cursor.position() == pos) return; cursor.setPosition(pos, QTextCursor::KeepAnchor); d->control->setTextCursor(cursor); } /*! \qmlproperty bool TextEdit::cursorVisible If true the text edit shows a cursor. This property is set and unset when the text edit gets focus, but it can also be set directly (useful, for example, if a KeyProxy might forward keys to it). */ bool QxTextEdit::isCursorVisible() const { Q_D(const QxTextEdit); return d->cursorVisible; } void QxTextEdit::setCursorVisible(bool on) { Q_D(QxTextEdit); if (d->cursorVisible == on) return; d->cursorVisible = on; QFocusEvent focusEvent(on ? QEvent::FocusIn : QEvent::FocusOut); if (!on && !d->persistentSelection) d->control->setCursorIsFocusIndicator(true); d->control->processEvent(&focusEvent, QPointF(0, -d->yoff)); emit cursorVisibleChanged(d->cursorVisible); } /*! \qmlproperty int TextEdit::cursorPosition The position of the cursor in the TextEdit. */ int QxTextEdit::cursorPosition() const { Q_D(const QxTextEdit); return d->control->textCursor().position(); } void QxTextEdit::setCursorPosition(int pos) { Q_D(QxTextEdit); QTextCursor cursor = d->control->textCursor(); if (cursor.position() == pos) return; cursor.setPosition(pos); d->control->setTextCursor(cursor); } /*! \qmlproperty Component TextEdit::cursorDelegate The delegate for the cursor in the TextEdit. If you set a cursorDelegate for a TextEdit, this delegate will be used for drawing the cursor instead of the standard cursor. An instance of the delegate will be created and managed by the text edit when a cursor is needed, and the x and y properties of delegate instance will be set so as to be one pixel before the top left of the current character. Note that the root item of the delegate component must be a QxItem or QxItem derived item. */ QDeclarativeComponent* QxTextEdit::cursorDelegate() const { Q_D(const QxTextEdit); return d->cursorComponent; } void QxTextEdit::setCursorDelegate(QDeclarativeComponent* c) { Q_D(QxTextEdit); if(d->cursorComponent){ if(d->cursor){ disconnect(d->control, SIGNAL(cursorPositionChanged()), this, SLOT(moveCursorDelegate())); d->control->setCursorWidth(-1); delete d->cursor; d->cursor = 0; } } d->cursorComponent = c; if(c && c->isReady()){ loadCursorDelegate(); }else{ if(c) connect(c, SIGNAL(statusChanged()), this, SLOT(loadCursorDelegate())); } emit cursorDelegateChanged(); } void QxTextEdit::loadCursorDelegate() { Q_D(QxTextEdit); if(d->cursorComponent->isLoading()) return; d->cursor = qobject_cast(d->cursorComponent->create(qmlContext(this))); if(d->cursor){ connect(d->control, SIGNAL(cursorPositionChanged()), this, SLOT(moveCursorDelegate())); d->control->setCursorWidth(0); QDeclarative_setParent_noEvent(d->cursor, this); d->cursor->setParentItem(this); d->cursor->setHeight(QFontMetrics(d->font).height()); moveCursorDelegate(); }else{ qmlInfo(this) << "Error loading cursor delegate."; } } /*! \qmlproperty int TextEdit::selectionStart The cursor position before the first character in the current selection. This property is read-only. To change the selection, use select(start,end), selectAll(), or selectWord(). \sa selectionEnd, cursorPosition, selectedText */ int QxTextEdit::selectionStart() const { Q_D(const QxTextEdit); return d->control->textCursor().selectionStart(); } /*! \qmlproperty int TextEdit::selectionEnd The cursor position after the last character in the current selection. This property is read-only. To change the selection, use select(start,end), selectAll(), or selectWord(). \sa selectionStart, cursorPosition, selectedText */ int QxTextEdit::selectionEnd() const { Q_D(const QxTextEdit); return d->control->textCursor().selectionEnd(); } /*! \qmlproperty string TextEdit::selectedText This read-only property provides the text currently selected in the text edit. It is equivalent to the following snippet, but is faster and easier to use. \code //myTextEdit is the id of the TextEdit myTextEdit.text.toString().substring(myTextEdit.selectionStart, myTextEdit.selectionEnd); \endcode */ QString QxTextEdit::selectedText() const { Q_D(const QxTextEdit); return d->control->textCursor().selectedText(); } /*! \qmlproperty bool TextEdit::focusOnPress Whether the TextEdit should gain focus on a mouse press. By default this is set to true. */ bool QxTextEdit::focusOnPress() const { Q_D(const QxTextEdit); return d->focusOnPress; } void QxTextEdit::setFocusOnPress(bool on) { Q_D(QxTextEdit); if (d->focusOnPress == on) return; d->focusOnPress = on; emit focusOnPressChanged(d->focusOnPress); } /*! \qmlproperty bool TextEdit::persistentSelection Whether the TextEdit should keep the selection visible when it loses focus to another item in the scene. By default this is set to true; */ bool QxTextEdit::persistentSelection() const { Q_D(const QxTextEdit); return d->persistentSelection; } void QxTextEdit::setPersistentSelection(bool on) { Q_D(QxTextEdit); if (d->persistentSelection == on) return; d->persistentSelection = on; emit persistentSelectionChanged(d->persistentSelection); } /* \qmlproperty real TextEdit::textMargin The margin, in pixels, around the text in the TextEdit. */ qreal QxTextEdit::textMargin() const { Q_D(const QxTextEdit); return d->textMargin; } void QxTextEdit::setTextMargin(qreal margin) { Q_D(QxTextEdit); if (d->textMargin == margin) return; d->textMargin = margin; d->document->setDocumentMargin(d->textMargin); emit textMarginChanged(d->textMargin); } void QxTextEdit::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry) { if (newGeometry.width() != oldGeometry.width()) updateSize(); QxPaintItem::geometryChanged(newGeometry, oldGeometry); } /*! Ensures any delayed caching or data loading the class needs to performed is complete. */ void QxTextEdit::componentComplete() { Q_D(QxTextEdit); QxPaintItem::componentComplete(); if (d->dirty) { updateSize(); d->dirty = false; } } /*! \qmlproperty bool TextEdit::selectByMouse Defaults to false. If true, the user can use the mouse to select text in some platform-specific way. Note that for some platforms this may not be an appropriate interaction (eg. may conflict with how the text needs to behave inside a Flickable. */ bool QxTextEdit::selectByMouse() const { Q_D(const QxTextEdit); return d->selectByMouse; } void QxTextEdit::setSelectByMouse(bool on) { Q_D(QxTextEdit); if (d->selectByMouse != on) { d->selectByMouse = on; emit selectByMouseChanged(on); } } /*! \qmlproperty bool TextEdit::readOnly Whether the user an interact with the TextEdit item. If this property is set to true the text cannot be edited by user interaction. By default this property is false. */ void QxTextEdit::setReadOnly(bool r) { Q_D(QxTextEdit); if (r == isReadOnly()) return; Qt::TextInteractionFlags flags = Qt::NoTextInteraction; if (r) { flags = Qt::TextSelectableByMouse; } else { flags = Qt::TextEditorInteraction; } d->control->setTextInteractionFlags(flags); if (!r) d->control->moveCursor(QTextCursor::End); emit readOnlyChanged(r); } bool QxTextEdit::isReadOnly() const { Q_D(const QxTextEdit); return !(d->control->textInteractionFlags() & Qt::TextEditable); } /*! Sets how the text edit should interact with user input to the given \a flags. */ void QxTextEdit::setTextInteractionFlags(Qt::TextInteractionFlags flags) { Q_D(QxTextEdit); d->control->setTextInteractionFlags(flags); } /*! Returns the flags specifying how the text edit should interact with user input. */ Qt::TextInteractionFlags QxTextEdit::textInteractionFlags() const { Q_D(const QxTextEdit); return d->control->textInteractionFlags(); } /*! \qmlproperty rectangle TextEdit::cursorRectangle The rectangle where the text cursor is rendered within the text edit. Read-only. */ QRect QxTextEdit::cursorRectangle() const { Q_D(const QxTextEdit); return d->control->cursorRect().toRect().translated(0,-d->yoff); } /*! \overload Handles the given \a event. */ bool QxTextEdit::event(QEvent *event) { Q_D(QxTextEdit); if (event->type() == QEvent::ShortcutOverride) { d->control->processEvent(event, QPointF(0, -d->yoff)); return event->isAccepted(); } return QxPaintItem::event(event); } /*! \overload Handles the given key \a event. */ void QxTextEdit::keyPressEvent(QKeyEvent *event) { Q_D(QxTextEdit); keyPressPreHandler(event); if (!event->isAccepted()) d->control->processEvent(event, QPointF(0, -d->yoff)); if (!event->isAccepted()) QxPaintItem::keyPressEvent(event); } /*! \overload Handles the given key \a event. */ void QxTextEdit::keyReleaseEvent(QKeyEvent *event) { Q_D(QxTextEdit); keyReleasePreHandler(event); if (!event->isAccepted()) d->control->processEvent(event, QPointF(0, -d->yoff)); if (!event->isAccepted()) QxPaintItem::keyReleaseEvent(event); } void QxTextEditPrivate::focusChanged(bool hasFocus) { Q_Q(QxTextEdit); q->setCursorVisible(hasFocus); QxItemPrivate::focusChanged(hasFocus); } /*! \qmlmethod void TextEdit::selectAll() Causes all text to be selected. */ void QxTextEdit::selectAll() { Q_D(QxTextEdit); d->control->selectAll(); } /*! \qmlmethod void TextEdit::selectWord() Causes the word closest to the current cursor position to be selected. */ void QxTextEdit::selectWord() { Q_D(QxTextEdit); QTextCursor c = d->control->textCursor(); c.select(QTextCursor::WordUnderCursor); d->control->setTextCursor(c); } /*! \qmlmethod void TextEdit::select(start,end) Causes the text from \a start to \a end to be selected. If either start or end is out of range, the selection is not changed. After calling this, selectionStart will become the lesser and selectionEnd will become the greater (regardless of the order passed to this method). \sa selectionStart, selectionEnd */ void QxTextEdit::select(int start, int end) { Q_D(QxTextEdit); if (start < 0 || end < 0 || start > d->text.length() || end > d->text.length()) return; QTextCursor cursor = d->control->textCursor(); cursor.beginEditBlock(); cursor.setPosition(start, QTextCursor::MoveAnchor); cursor.setPosition(end, QTextCursor::KeepAnchor); cursor.endEditBlock(); d->control->setTextCursor(cursor); // QTBUG-11100 updateSelectionMarkers(); } #ifndef QT_NO_CLIPBOARD /*! \qmlmethod TextEdit::cut() Moves the currently selected text to the system clipboard. */ void QxTextEdit::cut() { Q_D(QxTextEdit); d->control->cut(); } /*! \qmlmethod TextEdit::copy() Copies the currently selected text to the system clipboard. */ void QxTextEdit::copy() { Q_D(QxTextEdit); d->control->copy(); } /*! \qmlmethod TextEdit::paste() Relaces the currently selected text by the contents of the system clipboard. */ void QxTextEdit::paste() { Q_D(QxTextEdit); d->control->paste(); } #endif // QT_NO_CLIPBOARD /*! \overload Handles the given mouse \a event. */ void QxTextEdit::mousePressEvent(QGraphicsSceneMouseEvent *event) { Q_D(QxTextEdit); if (d->focusOnPress){ bool hadFocus = hasFocus(); forceFocus(); if (d->showInputPanelOnFocus) { if (hasFocus() && hadFocus && !isReadOnly()) { // re-open input panel on press if already focused openSoftwareInputPanel(); } } else { // show input panel on click if (hasFocus() && !hadFocus) { d->clickCausedFocus = true; } } } if (event->type() != QEvent::GraphicsSceneMouseDoubleClick || d->selectByMouse) d->control->processEvent(event, QPointF(0, -d->yoff)); if (!event->isAccepted()) QxPaintItem::mousePressEvent(event); } /*! \overload Handles the given mouse \a event. */ void QxTextEdit::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { Q_D(QxTextEdit); d->control->processEvent(event, QPointF(0, -d->yoff)); if (!d->showInputPanelOnFocus) { // input panel on click if (d->focusOnPress && !isReadOnly() && boundingRect().contains(event->pos())) { /* XXX if (QGraphicsView * view = qobject_cast(qApp->focusWidget())) { if (view->scene() && view->scene() == scene()) { qt_widget_private(view)->handleSoftwareInputPanel(event->button(), d->clickCausedFocus); } } */ } } d->clickCausedFocus = false; if (!event->isAccepted()) QxPaintItem::mouseReleaseEvent(event); } /*! \overload Handles the given mouse \a event. */ void QxTextEdit::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { Q_D(QxTextEdit); if (d->selectByMouse) { d->control->processEvent(event, QPointF(0, -d->yoff)); if (!event->isAccepted()) QxPaintItem::mouseDoubleClickEvent(event); } else { QxPaintItem::mouseDoubleClickEvent(event); } } /*! \overload Handles the given mouse \a event. */ void QxTextEdit::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { Q_D(QxTextEdit); if (d->selectByMouse) { d->control->processEvent(event, QPointF(0, -d->yoff)); if (!event->isAccepted()) QxPaintItem::mouseMoveEvent(event); event->setAccepted(true); } else { QxPaintItem::mouseMoveEvent(event); } } /*! \overload Handles the given input method \a event. */ void QxTextEdit::inputMethodEvent(QInputMethodEvent *event) { Q_D(QxTextEdit); d->control->processEvent(event, QPointF(0, -d->yoff)); } /*! \overload Returns the value of the given \a property. */ QVariant QxTextEdit::inputMethodQuery(Qt::InputMethodQuery property) const { Q_D(const QxTextEdit); return d->control->inputMethodQuery(property); } /*! Draws the contents of the text edit using the given \a painter within the given \a bounds. */ void QxTextEdit::paint(QPainter *painter) { Q_D(QxTextEdit); painter->setRenderHint(QPainter::TextAntialiasing, true); painter->translate(0,d->yoff); d->control->drawContents(painter, boundingRect().translated(0,-d->yoff)); painter->translate(0,-d->yoff); } void QxTextEdit::updateImgCache(const QRectF &rf) { Q_D(const QxTextEdit); QRect r; if (!rf.isValid()) { r = QRect(0,0,INT_MAX,INT_MAX); } else { r = rf.toRect(); if (r.height() > INT_MAX/2) { // Take care of overflow when translating "everything" r.setTop(r.y() + d->yoff); r.setBottom(INT_MAX/2); } else { r = r.translated(0,d->yoff); } } update(); } /*! \qmlproperty bool TextEdit::smooth This property holds whether the text is smoothly scaled or transformed. Smooth filtering gives better visual quality, but is slower. If the item is displayed at its natural size, this property has no visual or performance effect. \note Generally scaling artifacts are only visible if the item is stationary on the screen. A common pattern when animating an item is to disable smooth filtering at the beginning of the animation and reenable it at the conclusion. */ void QxTextEditPrivate::init() { Q_Q(QxTextEdit); q->setSmooth(smooth); q->setAcceptedMouseButtons(Qt::LeftButton); //q->setFlag(QGraphicsItem::ItemHasNoContents, false); //q->setFlag(QGraphicsItem::ItemAcceptsInputMethod); control = new QTextControl(q); control->setIgnoreUnusedNavigationEvents(true); // QTextControl follows the default text color // defined by the platform, declarative text // should be black by default QPalette pal = control->palette(); if (pal.color(QPalette::Text) != color) { pal.setColor(QPalette::Text, color); control->setPalette(pal); } QObject::connect(control, SIGNAL(updateRequest(QRectF)), q, SLOT(updateImgCache(QRectF))); QObject::connect(control, SIGNAL(textChanged()), q, SLOT(q_textChanged())); QObject::connect(control, SIGNAL(selectionChanged()), q, SIGNAL(selectionChanged())); QObject::connect(control, SIGNAL(selectionChanged()), q, SLOT(updateSelectionMarkers())); QObject::connect(control, SIGNAL(cursorPositionChanged()), q, SLOT(updateSelectionMarkers())); QObject::connect(control, SIGNAL(cursorPositionChanged()), q, SIGNAL(cursorPositionChanged())); QObject::connect(control, SIGNAL(cursorPositionChanged()), q, SIGNAL(cursorRectangleChanged())); document = control->document(); document->setDefaultFont(font); document->setDocumentMargin(textMargin); document->setUndoRedoEnabled(false); // flush undo buffer. document->setUndoRedoEnabled(true); updateDefaultTextOption(); } void QxTextEdit::q_textChanged() { Q_D(QxTextEdit); d->text = text(); updateSize(); //updateMicroFocus(); //XXX emit textChanged(d->text); } void QxTextEdit::moveCursorDelegate() { Q_D(QxTextEdit); if(!d->cursor) return; QRectF cursorRect = d->control->cursorRect(); d->cursor->setX(cursorRect.x()); d->cursor->setY(cursorRect.y()); } void QxTextEditPrivate::updateSelection() { Q_Q(QxTextEdit); QTextCursor cursor = control->textCursor(); bool startChange = (lastSelectionStart != cursor.selectionStart()); bool endChange = (lastSelectionEnd != cursor.selectionEnd()); cursor.beginEditBlock(); cursor.setPosition(lastSelectionStart, QTextCursor::MoveAnchor); cursor.setPosition(lastSelectionEnd, QTextCursor::KeepAnchor); cursor.endEditBlock(); control->setTextCursor(cursor); if(startChange) q->selectionStartChanged(); if(endChange) q->selectionEndChanged(); } void QxTextEdit::updateSelectionMarkers() { Q_D(QxTextEdit); if(d->lastSelectionStart != d->control->textCursor().selectionStart()){ d->lastSelectionStart = d->control->textCursor().selectionStart(); emit selectionStartChanged(); } if(d->lastSelectionEnd != d->control->textCursor().selectionEnd()){ d->lastSelectionEnd = d->control->textCursor().selectionEnd(); emit selectionEndChanged(); } //updateMicroFocus(); //XXX } //### we should perhaps be a bit smarter here -- depending on what has changed, we shouldn't // need to do all the calculations each time void QxTextEdit::updateSize() { Q_D(QxTextEdit); if (isComponentComplete()) { QFontMetrics fm = QFontMetrics(d->font); int dy = height(); // ### assumes that if the width is set, the text will fill to edges // ### (unless wrap is false, then clipping will occur) if (widthValid() && d->document->textWidth() != width()) d->document->setTextWidth(width()); dy -= (int)d->document->size().height(); if (heightValid()) { if (d->vAlign == AlignBottom) d->yoff = dy; else if (d->vAlign == AlignVCenter) d->yoff = dy/2; else d->yoff = 0; } else { d->yoff = 0; } setBaselineOffset(fm.ascent() + d->yoff + d->textMargin); //### need to comfirm cost of always setting these int newWidth = qCeil(d->document->idealWidth()); if (!widthValid() && d->document->textWidth() != newWidth) d->document->setTextWidth(newWidth); // ### Text does not align if width is not set (QTextDoc bug) int cursorWidth = 1; if(d->cursor) cursorWidth = d->cursor->width(); newWidth += cursorWidth; if(!d->document->isEmpty()) newWidth += 3;// ### Need a better way of accounting for space between char and cursor // ### Setting the implicitWidth triggers another updateSize(), and unless there are bindings nothing has changed. setImplicitWidth(newWidth); qreal newHeight = d->document->isEmpty() ? fm.height() : (int)d->document->size().height(); setImplicitHeight(newHeight); emit paintedSizeChanged(); } else { d->dirty = true; } update(); } void QxTextEditPrivate::updateDefaultTextOption() { QTextOption opt = document->defaultTextOption(); int oldAlignment = opt.alignment(); opt.setAlignment((Qt::Alignment)(int)(hAlign | vAlign)); QTextOption::WrapMode oldWrapMode = opt.wrapMode(); opt.setWrapMode(QTextOption::WrapMode(wrapMode)); if (oldWrapMode == opt.wrapMode() && oldAlignment == opt.alignment()) return; document->setDefaultTextOption(opt); } /*! \qmlmethod void TextEdit::openSoftwareInputPanel() Opens software input panels like virtual keyboards for typing, useful for customizing when you want the input keyboard to be shown and hidden in your application. By default the opening of input panels follows the platform style. On Symbian^1 and Symbian^3 -based devices the panels are opened by clicking TextEdit. On other platforms the panels are automatically opened when TextEdit element gains focus. Input panels are always closed if no editor owns focus. . You can disable the automatic behavior by setting the property \c focusOnPress to false and use functions openSoftwareInputPanel() and closeSoftwareInputPanel() to implement the behavior you want. Only relevant on platforms, which provide virtual keyboards. \code import Qt 4.7 TextEdit { id: textEdit text: "Hello world!" focusOnPress: false MouseArea { anchors.fill: parent onClicked: { if (!textEdit.focus) { textEdit.focus = true; textEdit.openSoftwareInputPanel(); } else { textEdit.focus = false; } } onPressAndHold: textEdit.closeSoftwareInputPanel(); } } \endcode */ void QxTextEdit::openSoftwareInputPanel() { QEvent event(QEvent::RequestSoftwareInputPanel); /* XXX if (qApp) { if (QGraphicsView * view = qobject_cast(qApp->focusWidget())) { if (view->scene() && view->scene() == scene()) { QApplication::sendEvent(view, &event); } } } */ } /*! \qmlmethod void TextEdit::closeSoftwareInputPanel() Closes a software input panel like a virtual keyboard shown on the screen, useful for customizing when you want the input keyboard to be shown and hidden in your application. By default the opening of input panels follows the platform style. On Symbian^1 and Symbian^3 -based devices the panels are opened by clicking TextEdit. On other platforms the panels are automatically opened when TextEdit element gains focus. Input panels are always closed if no editor owns focus. . You can disable the automatic behavior by setting the property \c focusOnPress to false and use functions openSoftwareInputPanel() and closeSoftwareInputPanel() to implement the behavior you want. Only relevant on platforms, which provide virtual keyboards. \code import Qt 4.7 TextEdit { id: textEdit text: "Hello world!" focusOnPress: false MouseArea { anchors.fill: parent onClicked: { if (!textEdit.focus) { textEdit.focus = true; textEdit.openSoftwareInputPanel(); } else { textEdit.focus = false; } } onPressAndHold: textEdit.closeSoftwareInputPanel(); } } \endcode */ void QxTextEdit::closeSoftwareInputPanel() { QEvent event(QEvent::CloseSoftwareInputPanel); /* XXX if (qApp) { if (QGraphicsView * view = qobject_cast(qApp->focusWidget())) { if (view->scene() && view->scene() == scene()) { QApplication::sendEvent(view, &event); } } } */ } void QxTextEdit::focusInEvent(QFocusEvent *event) { Q_D(const QxTextEdit); if (d->showInputPanelOnFocus) { if (d->focusOnPress && !isReadOnly()) { openSoftwareInputPanel(); } } QxPaintItem::focusInEvent(event); } QT_END_NAMESPACE