aboutsummaryrefslogtreecommitdiffstats
path: root/src/quick/items/qquicktextedit.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/quick/items/qquicktextedit.cpp')
-rw-r--r--src/quick/items/qquicktextedit.cpp823
1 files changed, 611 insertions, 212 deletions
diff --git a/src/quick/items/qquicktextedit.cpp b/src/quick/items/qquicktextedit.cpp
index 191a33167f..1d578a17f8 100644
--- a/src/quick/items/qquicktextedit.cpp
+++ b/src/quick/items/qquicktextedit.cpp
@@ -5,9 +5,8 @@
#include "qquicktextedit_p_p.h"
#include "qquicktextcontrol_p.h"
#include "qquicktextdocument_p.h"
-#include "qquickevents_p_p.h"
#include "qquickwindow.h"
-#include "qquicktextnode_p.h"
+#include "qsginternaltextnode_p.h"
#include "qquicktextnodeengine_p.h"
#include <QtCore/qmath.h>
@@ -23,6 +22,11 @@
#include <private/qqmlproperty_p.h>
#include <private/qtextengine_p.h>
#include <private/qsgadaptationlayer_p.h>
+#include <QtQuick/private/qquickpixmapcache_p.h>
+
+#if QT_CONFIG(accessibility)
+#include <private/qquickaccessibleattached_p.h>
+#endif
#include "qquicktextdocument.h"
@@ -33,6 +37,8 @@ QT_BEGIN_NAMESPACE
Q_DECLARE_LOGGING_CATEGORY(lcVP)
Q_LOGGING_CATEGORY(lcTextEdit, "qt.quick.textedit")
+using namespace Qt::StringLiterals;
+
/*!
\qmltype TextEdit
\instantiates QQuickTextEdit
@@ -79,7 +85,7 @@ TextEdit {
You can translate between cursor positions (characters from the start of the document) and pixel
points using positionAt() and positionToRectangle().
- \sa Text, TextInput
+ \sa Text, TextInput, TextArea, {Qt Quick Controls - Text Editor}
*/
/*!
@@ -101,22 +107,13 @@ static const int nodeBreakingSize = 300;
const int QQuickTextEditPrivate::largeTextSizeThreshold = QQUICKTEXT_LARGETEXT_THRESHOLD;
namespace {
- class ProtectedLayoutAccessor: public QAbstractTextDocumentLayout
- {
- public:
- inline QTextCharFormat formatAccessor(int pos)
- {
- return format(pos);
- }
- };
-
class RootNode : public QSGTransformNode
{
public:
RootNode() : cursorNode(nullptr), frameDecorationsNode(nullptr)
{ }
- void resetFrameDecorations(QQuickTextNode* newNode)
+ void resetFrameDecorations(QSGInternalTextNode* newNode)
{
if (frameDecorationsNode) {
removeChildNode(frameDecorationsNode);
@@ -139,7 +136,7 @@ namespace {
}
QSGInternalRectangleNode *cursorNode;
- QQuickTextNode* frameDecorationsNode;
+ QSGInternalTextNode* frameDecorationsNode;
};
}
@@ -151,6 +148,12 @@ QQuickTextEdit::QQuickTextEdit(QQuickItem *parent)
d->init();
}
+QQuickTextEdit::~QQuickTextEdit()
+{
+ Q_D(QQuickTextEdit);
+ qDeleteAll(d->pixmapsInProgress);
+}
+
QQuickTextEdit::QQuickTextEdit(QQuickTextEditPrivate &dd, QQuickItem *parent)
: QQuickImplicitSizeItem(dd, parent)
{
@@ -211,17 +214,16 @@ QString QQuickTextEdit::text() const
The requested weight of the font. The weight requested must be an integer
between 1 and 1000, or one of the predefined values:
- \list
- \li Font.Thin
- \li Font.Light
- \li Font.ExtraLight
- \li Font.Normal - the default
- \li Font.Medium
- \li Font.DemiBold
- \li Font.Bold
- \li Font.ExtraBold
- \li Font.Black
- \endlist
+
+ \value Font.Thin 100
+ \value Font.ExtraLight 200
+ \value Font.Light 300
+ \value Font.Normal 400 (default)
+ \value Font.Medium 500
+ \value Font.DemiBold 600
+ \value Font.Bold 700
+ \value Font.ExtraBold 800
+ \value Font.Black 900
\qml
TextEdit { text: "Hello"; font.weight: Font.DemiBold }
@@ -286,13 +288,12 @@ QString QQuickTextEdit::text() const
Sets the capitalization for the text.
- \list
- \li Font.MixedCase - This is the normal text rendering option where no capitalization change is applied.
- \li Font.AllUppercase - This alters the text to be rendered in all uppercase type.
- \li Font.AllLowercase - This alters the text to be rendered in all lowercase type.
- \li Font.SmallCaps - This alters the text to be rendered in small-caps type.
- \li Font.Capitalize - This alters the text to be rendered with the first character of each word as an uppercase character.
- \endlist
+ \value Font.MixedCase no capitalization change is applied
+ \value Font.AllUppercase alters the text to be rendered in all uppercase type
+ \value Font.AllLowercase alters the text to be rendered in all lowercase type
+ \value Font.SmallCaps alters the text to be rendered in small-caps type
+ \value Font.Capitalize alters the text to be rendered with the first character of
+ each word as an uppercase character
\qml
TextEdit { text: "Hello"; font.capitalization: Font.AllLowercase }
@@ -309,23 +310,21 @@ QString QQuickTextEdit::text() const
\note This property only has an effect when used together with render type TextEdit.NativeRendering.
- \list
- \li Font.PreferDefaultHinting - Use the default hinting level for the target platform.
- \li Font.PreferNoHinting - If possible, render text without hinting the outlines
- of the glyphs. The text layout will be typographically accurate, using the same metrics
- as are used e.g. when printing.
- \li Font.PreferVerticalHinting - If possible, render text with no horizontal hinting,
- but align glyphs to the pixel grid in the vertical direction. The text will appear
- crisper on displays where the density is too low to give an accurate rendering
- of the glyphs. But since the horizontal metrics of the glyphs are unhinted, the text's
- layout will be scalable to higher density devices (such as printers) without impacting
- details such as line breaks.
- \li Font.PreferFullHinting - If possible, render text with hinting in both horizontal and
- vertical directions. The text will be altered to optimize legibility on the target
- device, but since the metrics will depend on the target size of the text, the positions
- of glyphs, line breaks, and other typographical detail will not scale, meaning that a
- text layout may look different on devices with different pixel densities.
- \endlist
+ \value Font.PreferDefaultHinting Use the default hinting level for the target platform.
+ \value Font.PreferNoHinting If possible, render text without hinting the outlines
+ of the glyphs. The text layout will be typographically accurate, using the same metrics
+ as are used e.g. when printing.
+ \value Font.PreferVerticalHinting If possible, render text with no horizontal hinting,
+ but align glyphs to the pixel grid in the vertical direction. The text will appear
+ crisper on displays where the density is too low to give an accurate rendering
+ of the glyphs. But since the horizontal metrics of the glyphs are unhinted, the text's
+ layout will be scalable to higher density devices (such as printers) without impacting
+ details such as line breaks.
+ \value Font.PreferFullHinting If possible, render text with hinting in both horizontal and
+ vertical directions. The text will be altered to optimize legibility on the target
+ device, but since the metrics will depend on the target size of the text, the positions
+ of glyphs, line breaks, and other typographical detail will not scale, meaning that a
+ text layout may look different on devices with different pixel densities.
\qml
TextEdit { text: "Hello"; renderType: TextEdit.NativeRendering; font.hintingPreference: Font.PreferVerticalHinting }
@@ -363,6 +362,27 @@ QString QQuickTextEdit::text() const
*/
/*!
+ \qmlproperty object QtQuick::TextEdit::font.variableAxes
+ \since 6.7
+
+ \include qquicktext.cpp qml-font-variable-axes
+*/
+
+/*!
+ \qmlproperty object QtQuick::TextEdit::font.features
+ \since 6.6
+
+ \include qquicktext.cpp qml-font-features
+*/
+
+/*!
+ \qmlproperty object QtQuick::TextEdit::font.contextFontMerging
+ \since 6.8
+
+ \include qquicktext.cpp qml-font-context-font-merging
+*/
+
+/*!
\qmlproperty string QtQuick::TextEdit::text
The text to display. If the text format is AutoText the text edit will
@@ -376,7 +396,20 @@ QString QQuickTextEdit::text() const
remarkably better performance for modifying especially large rich text
content.
- \sa clear(), textFormat
+ Note that some keyboards use a predictive function. In this case,
+ the text being composed by the input method is not part of this property.
+ The part of the text related to the predictions is underlined and stored in
+ the \l preeditText property.
+
+ If you used \l TextDocument::source to load text, you can retrieve the
+ loaded text from this property. In that case, you can then change
+ \l textFormat to do format conversions that will change the value of the
+ \c text property. For example, if \c textFormat is \c RichText or
+ \c AutoText and you load an HTML file, then set \c textFormat to
+ \c MarkdownText afterwards, the \c text property will contain the
+ conversion from HTML to Markdown.
+
+ \sa clear(), preeditText, textFormat
*/
void QQuickTextEdit::setText(const QString &text)
{
@@ -384,7 +417,6 @@ void QQuickTextEdit::setText(const QString &text)
if (QQuickTextEdit::text() == text)
return;
- d->document->clearResources();
d->richText = d->format == RichText || (d->format == AutoText && Qt::mightBeRichText(text));
d->markdownText = d->format == MarkdownText;
if (!isComponentComplete()) {
@@ -426,6 +458,11 @@ void QQuickTextEdit::q_invalidate()
\since 5.7
This property contains partial text input from an input method.
+
+ To turn off partial text that results from predictions, set the \c Qt.ImhNoPredictiveText
+ flag in inputMethodHints.
+
+ \sa inputMethodHints
*/
QString QQuickTextEdit::preeditText() const
{
@@ -442,6 +479,7 @@ QString QQuickTextEdit::preeditText() const
\value TextEdit.PlainText (default) all styling tags are treated as plain text
\value TextEdit.AutoText detected via the Qt::mightBeRichText() heuristic
+ or the file format of \l TextDocument::source
\value TextEdit.RichText \l {Supported HTML Subset} {a subset of HTML 4}
\value TextEdit.MarkdownText \l {https://commonmark.org/help/}{CommonMark} plus the
\l {https://guides.github.com/features/mastering-markdown/}{GitHub}
@@ -449,9 +487,12 @@ QString QQuickTextEdit::preeditText() const
The default is \c TextEdit.PlainText. If the text format is set to
\c TextEdit.AutoText, the text edit will automatically determine whether
- the text should be treated as rich text. This determination is made using
- Qt::mightBeRichText(), which can detect the presence of an HTML tag on the
- first line of text, but cannot distinguish Markdown from plain text.
+ the text should be treated as rich text. If the \l text property is set,
+ this determination is made using Qt::mightBeRichText(), which can detect
+ the presence of an HTML tag on the first line of text, but cannot
+ distinguish Markdown from plain text. If the \l TextDocument::source
+ property is set, this determination is made from the
+ \l {QMimeDatabase::mimeTypeForFile()}{mime type of the file}.
\table
\row
@@ -464,14 +505,23 @@ QString QQuickTextEdit::preeditText() const
\l {https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown}{GitHub checkbox extension}
are interactively checkable.
- \note Interactively typing markup or markdown formatting is not supported.
+ If the \l TextDocument::source property is set, changing the \c textFormat
+ property after loading has the effect of converting from the detected
+ format to the requested format. For example, you can convert between HTML
+ and Markdown. However if either of those "rich" formats is loaded and then
+ you set \c textFormat to \c PlainText, the TextEdit will show the raw
+ markup. Thus, suitable bindings (e.g. to a checkable Control) can enable
+ the user to toggle back and forth between "raw" and WYSIWYG editing.
+
+ \note Interactively typing markup or markdown formatting in WYSIWYG mode
+ is not supported; but you can switch to \c PlainText, make changes, then
+ switch back to the appropriate \c textFormat.
\note With \c Text.MarkdownText, and with the supported subset of HTML,
some decorative elements are not rendered as they would be in a web browser:
\list
\li code blocks use the \l {QFontDatabase::FixedFont}{default monospace font} but without a surrounding highlight box
\li block quotes are indented, but there is no vertical line alongside the quote
- \li horizontal rules are not rendered
\endlist
*/
QQuickTextEdit::TextFormat QQuickTextEdit::textFormat() const
@@ -486,35 +536,135 @@ void QQuickTextEdit::setTextFormat(TextFormat format)
if (format == d->format)
return;
- const bool wasRich = d->richText;
- const bool wasMarkdown = d->markdownText;
- d->richText = format == RichText || (format == AutoText && (wasRich || Qt::mightBeRichText(text())));
- d->markdownText = format == MarkdownText;
+ auto mightBeRichText = [this]() {
+ return Qt::mightBeRichText(text());
+ };
+
+ auto findSourceFormat = [d, mightBeRichText](Qt::TextFormat detectedFormat) {
+ if (d->format == PlainText)
+ return PlainText;
+ if (d->richText) return RichText;
+ if (d->markdownText) return MarkdownText;
+ if (detectedFormat == Qt::AutoText && mightBeRichText())
+ return RichText;
+ return PlainText;
+ };
+
+ auto findDestinationFormat = [format, mightBeRichText](Qt::TextFormat detectedFormat, TextFormat sourceFormat) {
+ if (format == AutoText) {
+ if (detectedFormat == Qt::MarkdownText || (detectedFormat == Qt::AutoText && sourceFormat == MarkdownText))
+ return MarkdownText;
+ if (detectedFormat == Qt::RichText || (detectedFormat == Qt::AutoText && (sourceFormat == RichText || mightBeRichText())))
+ return RichText;
+ return PlainText; // fallback
+ }
+ return format;
+ };
+
+ bool textCachedChanged = false;
+ bool converted = false;
if (isComponentComplete()) {
-#if QT_CONFIG(texthtmlparser)
- if (wasRich && !d->richText && !d->markdownText) {
- d->control->setPlainText(!d->textCached ? d->control->toHtml() : d->text);
- updateSize();
- } else if (!wasRich && d->richText) {
- d->control->setHtml(!d->textCached ? d->control->toPlainText() : d->text);
- updateSize();
+ Qt::TextFormat detectedFormat = Qt::AutoText; // default if we don't know
+ if (d->quickDocument) {
+ // If QQuickTextDocument is in use, content can be loaded from a file,
+ // and then mime type detection overrides mightBeRichText().
+ detectedFormat = QQuickTextDocumentPrivate::get(d->quickDocument)->detectedFormat;
}
+
+ const TextFormat sourceFormat = findSourceFormat(detectedFormat);
+ const TextFormat destinationFormat = findDestinationFormat(detectedFormat, sourceFormat);
+
+ d->richText = destinationFormat == RichText;
+ d->markdownText = destinationFormat == MarkdownText;
+
+ // If converting between markdown and HTML, avoid using cached text: have QTD re-generate it
+ if (format != PlainText && (sourceFormat != destinationFormat)) {
+ d->textCached = false;
+ textCachedChanged = true;
+ }
+
+ switch (destinationFormat) {
+ case PlainText:
+#if QT_CONFIG(texthtmlparser)
+ if (sourceFormat == RichText) {
+ // If rich or unknown text was loaded and now the user wants plain text, get the raw HTML.
+ // But if we didn't set textCached to false above, assume d->text already contains HTML.
+ // This will allow the user to see the actual HTML they loaded (rather than Qt regenerating crufty HTML).
+ d->control->setPlainText(d->textCached ? d->text : d->control->toHtml());
+ converted = true;
+ }
#endif
#if QT_CONFIG(textmarkdownwriter) && QT_CONFIG(textmarkdownreader)
- if (wasMarkdown && !d->markdownText && !d->richText) {
- d->control->setPlainText(!d->textCached ? d->control->toMarkdown() : d->text);
- updateSize();
- } else if (!wasMarkdown && d->markdownText) {
- d->control->setMarkdownText(!d->textCached ? d->control->toPlainText() : d->text);
- updateSize();
- }
+ if (sourceFormat == MarkdownText) {
+ // If markdown or unknown text was loaded and now the user wants plain text, get the raw Markdown.
+ // But if we didn't set textCached to false above, assume d->text already contains markdown.
+ // This will allow the user to see the actual markdown they loaded.
+ d->control->setPlainText(d->textCached ? d->text : d->control->toMarkdown());
+ converted = true;
+ }
+#endif
+ break;
+ case RichText:
+#if QT_CONFIG(texthtmlparser)
+ switch (sourceFormat) {
+ case MarkdownText:
+ // If markdown was loaded and now the user wants HTML, convert markdown to HTML.
+ d->control->setHtml(d->control->toHtml());
+ converted = true;
+ break;
+ case PlainText:
+ // If plain text was loaded and now the user wants HTML, interpret plain text as HTML.
+ // But if we didn't set textCached to false above, assume d->text already contains HTML.
+ d->control->setHtml(d->textCached ? d->text : d->control->toPlainText());
+ converted = true;
+ break;
+ case AutoText:
+ case RichText: // nothing to do
+ break;
+ }
#endif
+ break;
+ case MarkdownText:
+#if QT_CONFIG(textmarkdownwriter) && QT_CONFIG(textmarkdownreader)
+ switch (sourceFormat) {
+ case RichText:
+ // If HTML was loaded and now the user wants markdown, convert HTML to markdown.
+ d->control->setMarkdownText(d->control->toMarkdown());
+ converted = true;
+ break;
+ case PlainText:
+ // If plain text was loaded and now the user wants markdown, interpret plain text as markdown.
+ // But if we didn't set textCached to false above, assume d->text already contains markdown.
+ d->control->setMarkdownText(d->textCached ? d->text : d->control->toPlainText());
+ converted = true;
+ break;
+ case AutoText:
+ case MarkdownText: // nothing to do
+ break;
+ }
+#endif
+ break;
+ case AutoText: // nothing to do
+ break;
+ }
+
+ if (converted)
+ updateSize();
+ } else {
+ d->richText = format == RichText || (format == AutoText && (d->richText || mightBeRichText()));
+ d->markdownText = format == MarkdownText;
}
+ qCDebug(lcTextEdit) << d->format << "->" << format
+ << "rich?" << d->richText << "md?" << d->markdownText
+ << "converted?" << converted << "cache invalidated?" << textCachedChanged;
+
d->format = format;
d->control->setAcceptRichText(d->format != PlainText);
emit textFormatChanged(d->format);
+ if (textCachedChanged)
+ emit textChanged();
}
/*!
@@ -523,16 +673,23 @@ void QQuickTextEdit::setTextFormat(TextFormat format)
Override the default rendering type for this component.
Supported render types are:
- \list
- \li Text.QtRendering
- \li Text.NativeRendering
- \endlist
- Select Text.NativeRendering if you prefer text to look native on the target platform and do
+ \value TextEdit.QtRendering Text is rendered using a scalable distance field for each glyph.
+ \value TextEdit.NativeRendering Text is rendered using a platform-specific technique.
+ \value TextEdit.CurveRendering Text is rendered using a curve rasterizer running directly on
+ the graphics hardware. (Introduced in Qt 6.7.0.)
+
+ Select \c TextEdit.NativeRendering if you prefer text to look native on the target platform and do
not require advanced features such as transformation of the text. Using such features in
combination with the NativeRendering render type will lend poor and sometimes pixelated
results.
+ Both \c TextEdit.QtRendering and \c TextEdit.CurveRendering are hardware-accelerated techniques.
+ \c QtRendering is the faster of the two, but uses more memory and will exhibit rendering
+ artifacts at large sizes. \c CurveRendering should be considered as an alternative in cases
+ where \c QtRendering does not give good visual results or where reducing graphics memory
+ consumption is a priority.
+
The default rendering type is determined by \l QQuickWindow::textRenderType().
*/
QQuickTextEdit::RenderType QQuickTextEdit::renderType() const
@@ -678,19 +835,21 @@ void QQuickTextEdit::setSelectedTextColor(const QColor &color)
the left.
Valid values for \c horizontalAlignment are:
- \list
- \li TextEdit.AlignLeft (default)
- \li TextEdit.AlignRight
- \li TextEdit.AlignHCenter
- \li TextEdit.AlignJustify
- \endlist
+
+ \value TextEdit.AlignLeft
+ left alignment with ragged edges on the right (default)
+ \value TextEdit.AlignRight
+ align each line to the right with ragged edges on the left
+ \value TextEdit.AlignHCenter
+ align each line to the center
+ \value TextEdit.AlignJustify
+ align each line to both right and left, spreading out words as necessary
Valid values for \c verticalAlignment are:
- \list
- \li TextEdit.AlignTop (default)
- \li TextEdit.AlignBottom
- \li TextEdit.AlignVCenter
- \endlist
+
+ \value TextEdit.AlignTop start at the top of the item (default)
+ \value TextEdit.AlignBottom align the last line to the bottom and other lines above
+ \value TextEdit.AlignVCenter align the center vertically
When using the attached property LayoutMirroring::enabled to mirror application
layouts, the horizontal alignment of text will also be mirrored. However, the property
@@ -706,11 +865,11 @@ QQuickTextEdit::HAlignment QQuickTextEdit::hAlign() const
void QQuickTextEdit::setHAlign(HAlignment align)
{
Q_D(QQuickTextEdit);
- bool forceAlign = d->hAlignImplicit && d->effectiveLayoutMirror;
- d->hAlignImplicit = false;
- if (d->setHAlign(align, forceAlign) && isComponentComplete()) {
+
+ if (d->setHAlign(align, true) && isComponentComplete()) {
d->updateDefaultTextOption();
updateSize();
+ updateWholeDocument();
}
}
@@ -743,21 +902,34 @@ QQuickTextEdit::HAlignment QQuickTextEdit::effectiveHAlign() const
return effectiveAlignment;
}
-bool QQuickTextEditPrivate::setHAlign(QQuickTextEdit::HAlignment alignment, bool forceAlign)
+bool QQuickTextEditPrivate::setHAlign(QQuickTextEdit::HAlignment align, bool forceAlign)
{
Q_Q(QQuickTextEdit);
- if (hAlign != alignment || forceAlign) {
- QQuickTextEdit::HAlignment oldEffectiveHAlign = q->effectiveHAlign();
- hAlign = alignment;
- emit q->horizontalAlignmentChanged(alignment);
- if (oldEffectiveHAlign != q->effectiveHAlign())
- emit q->effectiveHorizontalAlignmentChanged();
+ if (hAlign == align && !forceAlign)
+ return false;
+
+ const bool wasImplicit = hAlignImplicit;
+ const auto oldEffectiveHAlign = q->effectiveHAlign();
+
+ hAlignImplicit = !forceAlign;
+ if (hAlign != align) {
+ hAlign = align;
+ emit q->horizontalAlignmentChanged(align);
+ }
+
+ if (q->effectiveHAlign() != oldEffectiveHAlign) {
+ emit q->effectiveHorizontalAlignmentChanged();
return true;
}
+
+ if (forceAlign && wasImplicit) {
+ // QTBUG-120052 - when horizontal text alignment is set explicitly,
+ // we need notify any other controls that may depend on it, like QQuickPlaceholderText
+ emit q->effectiveHorizontalAlignmentChanged();
+ }
return false;
}
-
Qt::LayoutDirection QQuickTextEditPrivate::textDirection(const QString &text) const
{
const QChar *character = text.constData();
@@ -780,20 +952,24 @@ Qt::LayoutDirection QQuickTextEditPrivate::textDirection(const QString &text) co
bool QQuickTextEditPrivate::determineHorizontalAlignment()
{
Q_Q(QQuickTextEdit);
- if (hAlignImplicit && q->isComponentComplete()) {
- Qt::LayoutDirection direction = contentDirection;
+ if (!hAlignImplicit || !q->isComponentComplete())
+ return false;
+
+ Qt::LayoutDirection direction = contentDirection;
#if QT_CONFIG(im)
- if (direction == Qt::LayoutDirectionAuto) {
- const QString preeditText = control->textCursor().block().layout()->preeditAreaText();
- direction = textDirection(preeditText);
- }
- if (direction == Qt::LayoutDirectionAuto)
- direction = qGuiApp->inputMethod()->inputDirection();
+ if (direction == Qt::LayoutDirectionAuto) {
+ QTextBlock block = control->textCursor().block();
+ if (!block.layout())
+ return false;
+ direction = textDirection(block.layout()->preeditAreaText());
+ }
+ if (direction == Qt::LayoutDirectionAuto)
+ direction = qGuiApp->inputMethod()->inputDirection();
#endif
- return setHAlign(direction == Qt::RightToLeft ? QQuickTextEdit::AlignRight : QQuickTextEdit::AlignLeft);
- }
- return false;
+ const auto implicitHAlign = direction == Qt::RightToLeft ?
+ QQuickTextEdit::AlignRight : QQuickTextEdit::AlignLeft;
+ return setHAlign(implicitHAlign);
}
void QQuickTextEditPrivate::mirrorChange()
@@ -840,6 +1016,26 @@ Qt::InputMethodHints QQuickTextEditPrivate::effectiveInputMethodHints() const
}
#endif
+#if QT_CONFIG(accessibility)
+void QQuickTextEditPrivate::accessibilityActiveChanged(bool active)
+{
+ if (!active)
+ return;
+
+ Q_Q(QQuickTextEdit);
+ if (QQuickAccessibleAttached *accessibleAttached = qobject_cast<QQuickAccessibleAttached *>(
+ qmlAttachedPropertiesObject<QQuickAccessibleAttached>(q, true))) {
+ accessibleAttached->setRole(effectiveAccessibleRole());
+ accessibleAttached->set_readOnly(q->isReadOnly());
+ }
+}
+
+QAccessible::Role QQuickTextEditPrivate::accessibleRole() const
+{
+ return QAccessible::EditableText;
+}
+#endif
+
void QQuickTextEditPrivate::setTopPadding(qreal value, bool reset)
{
Q_Q(QQuickTextEdit);
@@ -930,20 +1126,26 @@ void QQuickTextEdit::setVAlign(QQuickTextEdit::VAlignment alignment)
moveCursorDelegate();
emit verticalAlignmentChanged(d->vAlign);
}
+
/*!
\qmlproperty enumeration QtQuick::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
- \li TextEdit.NoWrap - no wrapping will be performed. If the text contains insufficient newlines, then implicitWidth will exceed a set width.
- \li TextEdit.WordWrap - wrapping is done on word boundaries only. If a word is too long, implicitWidth will exceed a set width.
- \li TextEdit.WrapAnywhere - wrapping is done at any point on a line, even if it occurs in the middle of a word.
- \li 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
+ \value TextEdit.NoWrap
+ (default) no wrapping will be performed. If the text contains insufficient newlines,
+ \l {Item::}{implicitWidth} will exceed a set width.
+ \value TextEdit.WordWrap
+ wrapping is done on word boundaries only. If a word is too long,
+ \l {Item::}{implicitWidth} will exceed a set width.
+ \value TextEdit.WrapAnywhere
+ wrapping is done at any point on a line, even if it occurs in the middle of a word.
+ \value 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.
- The default is TextEdit.NoWrap. If you set a width, consider using TextEdit.Wrap.
+ The default is \c TextEdit.NoWrap. If you set a width, consider using \c TextEdit.Wrap.
*/
QQuickTextEdit::WrapMode QQuickTextEdit::wrapMode() const
{
@@ -1107,6 +1309,24 @@ int QQuickTextEdit::positionAt(qreal x, qreal y) const
}
/*!
+ \qmlproperty QtQuick::TextSelection QtQuick::TextEdit::cursorSelection
+ \since 6.7
+ \preliminary
+
+ This property is an object that provides properties of the text that is
+ currently selected, if any, alongside the text cursor.
+
+ \sa selectedText, selectionStart, selectionEnd
+*/
+QQuickTextSelection *QQuickTextEdit::cursorSelection() const
+{
+ Q_D(const QQuickTextEdit);
+ if (!d->cursorSelection)
+ d->cursorSelection = new QQuickTextSelection(const_cast<QQuickTextEdit *>(this));
+ return d->cursorSelection;
+}
+
+/*!
\qmlmethod QtQuick::TextEdit::moveCursorSelection(int position, SelectionMode mode)
Moves the cursor to \a position and updates the selection according to the optional \a mode
@@ -1120,13 +1340,12 @@ int QQuickTextEdit::positionAt(qreal x, qreal y) const
The selection mode specifies whether the selection is updated on a per character or a per word
basis. If not specified the selection mode will default to \c {TextEdit.SelectCharacters}.
- \list
- \li TextEdit.SelectCharacters - Sets either the selectionStart or selectionEnd (whichever was at
- the previous cursor position) to the specified position.
- \li TextEdit.SelectWords - Sets the selectionStart and selectionEnd to include all
- words between the specified position and the previous cursor position. Words partially in the
- range are included.
- \endlist
+ \value TextEdit.SelectCharacters
+ Sets either the selectionStart or selectionEnd (whichever was at the previous cursor position)
+ to the specified position.
+ \value TextEdit.SelectWords
+ Sets the selectionStart and selectionEnd to include all words between the specified position
+ and the previous cursor position. Words partially in the range are included.
For example, take this sequence of calls:
@@ -1424,38 +1643,31 @@ void QQuickTextEdit::setTextMargin(qreal margin)
Flags that alter behaviour are:
- \list
- \li Qt.ImhHiddenText - Characters should be hidden, as is typically used when entering passwords.
- \li Qt.ImhSensitiveData - Typed text should not be stored by the active input method
- in any persistent storage like predictive user dictionary.
- \li Qt.ImhNoAutoUppercase - The input method should not try to automatically switch to upper case
- when a sentence ends.
- \li Qt.ImhPreferNumbers - Numbers are preferred (but not required).
- \li Qt.ImhPreferUppercase - Upper case letters are preferred (but not required).
- \li Qt.ImhPreferLowercase - Lower case letters are preferred (but not required).
- \li Qt.ImhNoPredictiveText - Do not use predictive text (i.e. dictionary lookup) while typing.
-
- \li Qt.ImhDate - The text editor functions as a date field.
- \li Qt.ImhTime - The text editor functions as a time field.
- \endlist
+ \value Qt.ImhHiddenText Characters should be hidden, as is typically used when entering passwords.
+ \value Qt.ImhSensitiveData Typed text should not be stored by the active input method
+ in any persistent storage like predictive user dictionary.
+ \value Qt.ImhNoAutoUppercase The input method should not try to automatically switch to
+ upper case when a sentence ends.
+ \value Qt.ImhPreferNumbers Numbers are preferred (but not required).
+ \value Qt.ImhPreferUppercase Upper case letters are preferred (but not required).
+ \value Qt.ImhPreferLowercase Lower case letters are preferred (but not required).
+ \value Qt.ImhNoPredictiveText Do not use predictive text (i.e. dictionary lookup) while typing.
+ \value Qt.ImhDate The text editor functions as a date field.
+ \value Qt.ImhTime The text editor functions as a time field.
Flags that restrict input (exclusive flags) are:
- \list
- \li Qt.ImhDigitsOnly - Only digits are allowed.
- \li Qt.ImhFormattedNumbersOnly - Only number input is allowed. This includes decimal point and minus sign.
- \li Qt.ImhUppercaseOnly - Only upper case letter input is allowed.
- \li Qt.ImhLowercaseOnly - Only lower case letter input is allowed.
- \li Qt.ImhDialableCharactersOnly - Only characters suitable for phone dialing are allowed.
- \li Qt.ImhEmailCharactersOnly - Only characters suitable for email addresses are allowed.
- \li Qt.ImhUrlCharactersOnly - Only characters suitable for URLs are allowed.
- \endlist
+ \value Qt.ImhDigitsOnly Only digits are allowed.
+ \value Qt.ImhFormattedNumbersOnly Only number input is allowed. This includes decimal point and minus sign.
+ \value Qt.ImhUppercaseOnly Only upper case letter input is allowed.
+ \value Qt.ImhLowercaseOnly Only lower case letter input is allowed.
+ \value Qt.ImhDialableCharactersOnly Only characters suitable for phone dialing are allowed.
+ \value Qt.ImhEmailCharactersOnly Only characters suitable for email addresses are allowed.
+ \value Qt.ImhUrlCharactersOnly Only characters suitable for URLs are allowed.
Masks:
- \list
- \li Qt.ImhExclusiveInputMask - This mask yields nonzero if any of the exclusive flags are used.
- \endlist
+ \value Qt.ImhExclusiveInputMask This mask yields nonzero if any of the exclusive flags are used.
*/
Qt::InputMethodHints QQuickTextEdit::inputMethodHints() const
@@ -1487,14 +1699,35 @@ void QQuickTextEdit::setInputMethodHints(Qt::InputMethodHints hints)
void QQuickTextEdit::geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry)
{
Q_D(QQuickTextEdit);
- if (!d->inLayout && ((newGeometry.width() != oldGeometry.width() && widthValid())
- || (newGeometry.height() != oldGeometry.height() && heightValid()))) {
+ if (!d->inLayout && ((newGeometry.width() != oldGeometry.width())
+ || (newGeometry.height() != oldGeometry.height()))) {
updateSize();
updateWholeDocument();
- moveCursorDelegate();
+ if (widthValid() || heightValid())
+ moveCursorDelegate();
}
QQuickImplicitSizeItem::geometryChange(newGeometry, oldGeometry);
+}
+
+void QQuickTextEdit::itemChange(ItemChange change, const ItemChangeData &value)
+{
+ Q_D(QQuickTextEdit);
+ Q_UNUSED(value);
+ switch (change) {
+ case ItemDevicePixelRatioHasChanged:
+ if (d->renderType == NativeRendering) {
+ // Native rendering optimizes for a given pixel grid, so its results must not be scaled.
+ // Text layout code respects the current device pixel ratio automatically, we only need
+ // to rerun layout after the ratio changed.
+ updateSize();
+ updateWholeDocument();
+ }
+ break;
+ default:
+ break;
+ }
+ QQuickImplicitSizeItem::itemChange(change, value);
}
/*!
@@ -1509,20 +1742,17 @@ void QQuickTextEdit::componentComplete()
const QUrl url = baseUrl();
const QQmlContext *context = qmlContext(this);
d->document->setBaseUrl(context ? context->resolvedUrl(url) : url);
+ if (!d->text.isEmpty()) {
#if QT_CONFIG(texthtmlparser)
- if (d->richText)
- d->control->setHtml(d->text);
- else
+ if (d->richText)
+ d->control->setHtml(d->text);
+ else
#endif
#if QT_CONFIG(textmarkdownreader)
- if (d->markdownText)
- d->control->setMarkdownText(d->text);
- else
-#endif
- if (!d->text.isEmpty()) {
if (d->markdownText)
d->control->setMarkdownText(d->text);
else
+#endif
d->control->setPlainText(d->text);
}
@@ -1535,6 +1765,17 @@ void QQuickTextEdit::componentComplete()
if (d->cursorComponent && isCursorVisible())
QQuickTextUtil::createCursor(d);
polish();
+
+#if QT_CONFIG(accessibility)
+ if (QAccessible::isActive())
+ d->accessibilityActiveChanged(true);
+#endif
+}
+
+int QQuickTextEdit::resourcesLoading() const
+{
+ Q_D(const QQuickTextEdit);
+ return d->pixmapsInProgress.size();
}
/*!
@@ -1627,10 +1868,8 @@ void QQuickTextEdit::setSelectByMouse(bool on)
Specifies how text should be selected using a mouse.
- \list
- \li TextEdit.SelectCharacters - The selection is updated with individual characters. (Default)
- \li TextEdit.SelectWords - The selection is updated with whole words.
- \endlist
+ \value TextEdit.SelectCharacters (default) The selection is updated with individual characters.
+ \value TextEdit.SelectWords The selection is updated with whole words.
This property only applies when \l selectByMouse is true.
*/
@@ -1694,6 +1933,13 @@ void QQuickTextEdit::setReadOnly(bool r)
} else if (hasActiveFocus()) {
setCursorVisible(true);
}
+
+#if QT_CONFIG(accessibility)
+ if (QAccessible::isActive()) {
+ if (QQuickAccessibleAttached *accessibleAttached = QQuickAccessibleAttached::attachedProperties(this))
+ accessibleAttached->set_readOnly(r);
+ }
+#endif
}
bool QQuickTextEdit::isReadOnly() const
@@ -2055,6 +2301,87 @@ void QQuickTextEdit::triggerPreprocess()
update();
}
+/*! \internal
+ QTextDocument::loadResource() calls this to load inline images etc.
+ But if it's a local file, don't do it: let QTextDocument::loadResource()
+ load it in the default way. QQuickPixmap is for QtQuick-specific uses.
+*/
+QVariant QQuickTextEdit::loadResource(int type, const QUrl &source)
+{
+ Q_D(QQuickTextEdit);
+ const QUrl url = d->document->baseUrl().resolved(source);
+ if (url.isLocalFile()) {
+ // qmlWarning if the file doesn't exist (because QTextDocument::loadResource() can't do that)
+ QFileInfo fi(QQmlFile::urlToLocalFileOrQrc(url));
+ if (!fi.exists())
+ qmlWarning(this) << "Cannot open: " << url.toString();
+ // let QTextDocument::loadResource() handle local file loading
+ return {};
+ }
+
+ // see if we already started a load job
+ auto existingJobIter = std::find_if(
+ d->pixmapsInProgress.cbegin(), d->pixmapsInProgress.cend(),
+ [&url](const auto *job) { return job->url() == url; } );
+ if (existingJobIter != d->pixmapsInProgress.cend()) {
+ const QQuickPixmap *job = *existingJobIter;
+ if (job->isError()) {
+ qmlWarning(this) << job->error();
+ d->pixmapsInProgress.erase(existingJobIter);
+ delete job;
+ return QImage();
+ } else {
+ qCDebug(lcTextEdit) << "already downloading" << url;
+ // existing job: return a null variant if it's not done yet
+ return job->isReady() ? job->image() : QVariant();
+ }
+ }
+
+ // not found: start a new load job
+ qCDebug(lcTextEdit) << "loading" << source << "resolved" << url
+ << "type" << static_cast<QTextDocument::ResourceType>(type);
+ QQmlContext *context = qmlContext(this);
+ Q_ASSERT(context);
+ // don't cache it in QQuickPixmapCache, because it's cached in QTextDocumentPrivate::cachedResources
+ QQuickPixmap *p = new QQuickPixmap(context->engine(), url, QQuickPixmap::Options{});
+ p->connectFinished(this, SLOT(resourceRequestFinished()));
+ d->pixmapsInProgress.append(p);
+ // the new job is probably not done; return a null variant if the caller should poll again
+ return p->isReady() ? p->image() : QVariant();
+}
+
+/*! \internal
+ Handle completion of a download that QQuickTextEdit::loadResource() started.
+*/
+void QQuickTextEdit::resourceRequestFinished()
+{
+ Q_D(QQuickTextEdit);
+ for (auto it = d->pixmapsInProgress.cbegin(); it != d->pixmapsInProgress.cend(); ++it) {
+ auto *job = *it;
+ if (job->isError()) {
+ // get QTextDocument::loadResource() to call QQuickTextEdit::loadResource() again, to return the placeholder
+ qCDebug(lcTextEdit) << "failed to load (error)" << job->url();
+ d->document->resource(QTextDocument::ImageResource, job->url());
+ // that will call QQuickTextEdit::loadResource() which will delete the job;
+ // so leave it in pixmapsInProgress for now, and stop this loop
+ break;
+ } else if (job->isReady()) {
+ // get QTextDocument::loadResource() to call QQuickTextEdit::loadResource() again, and cache the result
+ auto res = d->document->resource(QTextDocument::ImageResource, job->url());
+ // If QTextDocument::resource() returned a valid variant, it's been cached too. Either way, the job is done.
+ qCDebug(lcTextEdit) << (res.isValid() ? "done downloading" : "failed to load") << job->url() << job->rect();
+ d->pixmapsInProgress.erase(it);
+ delete job;
+ break;
+ }
+ }
+ if (d->pixmapsInProgress.isEmpty()) {
+ invalidate();
+ updateSize();
+ q_invalidate();
+ }
+}
+
typedef QQuickTextEditPrivate::Node TextNode;
using TextNodeIterator = QQuickTextEditPrivate::TextNodeIterator;
@@ -2063,7 +2390,7 @@ static inline bool operator<(const TextNode &n1, const TextNode &n2)
return n1.startPos() < n2.startPos();
}
-static inline void updateNodeTransform(QQuickTextNode* node, const QPointF &topLeft)
+static inline void updateNodeTransform(QSGInternalTextNode *node, const QPointF &topLeft)
{
QMatrix4x4 transformMatrix;
transformMatrix.translate(topLeft.x(), topLeft.y());
@@ -2089,6 +2416,22 @@ void QQuickTextEdit::invalidateFontCaches()
}
}
+QTextDocument *QQuickTextEdit::document() const
+{
+ Q_D(const QQuickTextEdit);
+ return d->document;
+}
+
+void QQuickTextEdit::setDocument(QTextDocument *doc)
+{
+ Q_D(QQuickTextEdit);
+ if (d->ownsDocument)
+ delete d->document;
+ d->document = doc;
+ d->ownsDocument = false;
+ d->control->setDocument(doc);
+}
+
inline void resetEngine(QQuickTextNodeEngine *engine, const QColor& textColor, const QColor& selectedTextColor, const QColor& selectionColor)
{
*engine = QQuickTextNodeEngine();
@@ -2114,7 +2457,7 @@ QSGNode *QQuickTextEdit::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *
delete oldNode;
oldNode = nullptr;
- // If we had any QQuickTextNode node references, they were deleted along with the root node
+ // If we had any QSGInternalTextNode node references, they were deleted along with the root node
// But here we must delete the Node structures in textNodeMap
d->textNodeMap.clear();
}
@@ -2123,6 +2466,10 @@ QSGNode *QQuickTextEdit::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *
RootNode *rootNode = static_cast<RootNode *>(oldNode);
TextNodeIterator nodeIterator = d->textNodeMap.begin();
+ std::optional<int> firstPosAcrossAllNodes;
+ if (nodeIterator != d->textNodeMap.end())
+ firstPosAcrossAllNodes = nodeIterator->startPos();
+
while (nodeIterator != d->textNodeMap.end() && !nodeIterator->dirty())
++nodeIterator;
@@ -2139,7 +2486,7 @@ QSGNode *QQuickTextEdit::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *
firstDirtyPos = nodeIterator->startPos();
// ### this could be optimized if the first and last dirty nodes are not connected
// as the intermediate text nodes would usually only need to be transformed differently.
- QQuickTextNode *firstCleanNode = nullptr;
+ QSGInternalTextNode *firstCleanNode = nullptr;
auto it = d->textNodeMap.constEnd();
while (it != nodeIterator) {
--it;
@@ -2165,7 +2512,7 @@ QSGNode *QQuickTextEdit::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *
rootNode->resetFrameDecorations(d->createTextNode());
resetEngine(&frameDecorationsEngine, d->color, d->selectedTextColor, d->selectionColor);
- QQuickTextNode *node = nullptr;
+ QSGInternalTextNode *node = nullptr;
int currentNodeSize = 0;
int nodeStart = firstDirtyPos;
@@ -2184,14 +2531,17 @@ QSGNode *QQuickTextEdit::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *
d->firstBlockInViewport = -1;
d->firstBlockPastViewport = -1;
+ int frameCount = -1;
while (!frames.isEmpty()) {
QTextFrame *textFrame = frames.takeFirst();
+ ++frameCount;
+ if (frameCount > 0)
+ firstDirtyPos = 0;
+ qCDebug(lcVP) << "frame" << frameCount << textFrame
+ << "from" << positionToRectangle(textFrame->firstPosition()).topLeft()
+ << "to" << positionToRectangle(textFrame->lastPosition()).bottomRight();
frames.append(textFrame->childFrames());
frameDecorationsEngine.addFrameDecorations(d->document, textFrame);
-
- if (textFrame->lastPosition() < firstDirtyPos
- || textFrame->firstPosition() >= firstCleanNode.startPos())
- continue;
resetEngine(&engine, d->color, d->selectedTextColor, d->selectionColor);
if (textFrame->firstPosition() > textFrame->lastPosition()
@@ -2199,7 +2549,7 @@ QSGNode *QQuickTextEdit::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *
node = d->createTextNode();
updateNodeTransform(node, d->document->documentLayout()->frameBoundingRect(textFrame).topLeft());
const int pos = textFrame->firstPosition() - 1;
- ProtectedLayoutAccessor *a = static_cast<ProtectedLayoutAccessor *>(d->document->documentLayout());
+ auto *a = static_cast<QtPrivate::ProtectedLayoutAccessor *>(d->document->documentLayout());
QTextCharFormat format = a->formatAccessor(pos);
QTextBlock block = textFrame->firstCursorPosition().block();
nodeOffset = d->document->documentLayout()->blockBoundingRect(block).topLeft();
@@ -2241,7 +2591,8 @@ QSGNode *QQuickTextEdit::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *
coveredRegion = block.layout()->boundingRect().adjusted(nodeOffset.x(), nodeOffset.y(), nodeOffset.x(), nodeOffset.y());
inView = coveredRegion.bottom() > viewport.top();
}
- if (d->firstBlockInViewport < 0 && inView) {
+ const bool potentiallyScrollingBackwards = firstPosAcrossAllNodes && *firstPosAcrossAllNodes == firstDirtyPos;
+ if (d->firstBlockInViewport < 0 && inView && potentiallyScrollingBackwards) {
// During backward scrolling, we need to iterate backwards from textNodeMap.begin() to fill the top of the viewport.
if (coveredRegion.top() > viewport.top() + 1) {
qCDebug(lcVP) << "checking backwards from block" << block.blockNumber() << "@" << nodeOffset.y() << coveredRegion;
@@ -2261,7 +2612,6 @@ QSGNode *QQuickTextEdit::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *
}
}
qCDebug(lcVP) << "first block in viewport" << block.blockNumber() << "@" << nodeOffset.y() << coveredRegion;
- d->firstBlockInViewport = block.blockNumber();
if (block.layout())
d->renderedRegion = coveredRegion;
} else {
@@ -2274,9 +2624,16 @@ QSGNode *QQuickTextEdit::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *
}
break; // skip rest of blocks in this frame
}
- if (inView && !block.text().isEmpty() && coveredRegion.isValid())
+ if (inView && !block.text().isEmpty() && coveredRegion.isValid()) {
d->renderedRegion = d->renderedRegion.united(coveredRegion);
+ // In case we're going to visit more (nested) frames after this, ensure that we
+ // don't omit any blocks that fit within the region that we claim as fully rendered.
+ if (!frames.isEmpty())
+ viewport = viewport.united(d->renderedRegion);
+ }
}
+ if (inView && d->firstBlockInViewport < 0)
+ d->firstBlockInViewport = block.blockNumber();
}
bool createdNodeInView = false;
@@ -2420,12 +2777,7 @@ bool QQuickTextEdit::isInputMethodComposing() const
}
QQuickTextEditPrivate::ExtraData::ExtraData()
- : padding(0)
- , topPadding(0)
- , leftPadding(0)
- , rightPadding(0)
- , bottomPadding(0)
- , explicitTopPadding(false)
+ : explicitTopPadding(false)
, explicitLeftPadding(false)
, explicitRightPadding(false)
, explicitBottomPadding(false)
@@ -2451,7 +2803,10 @@ void QQuickTextEditPrivate::init()
q->setAcceptHoverEvents(true);
- document = new QQuickTextDocumentWithImageResources(q);
+ document = new QTextDocument(q);
+ ownsDocument = true;
+ auto *imageHandler = new QQuickTextImageHandler(document);
+ document->documentLayout()->registerHandler(QTextFormat::ImageObject, imageHandler);
control = new QQuickTextControl(document, q);
control->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard | Qt::TextEditable);
@@ -2472,10 +2827,9 @@ void QQuickTextEditPrivate::init()
#if QT_CONFIG(clipboard)
qmlobject_connect(QGuiApplication::clipboard(), QClipboard, SIGNAL(dataChanged()), q, QQuickTextEdit, SLOT(q_canPasteChanged()));
#endif
- qmlobject_connect(document, QQuickTextDocumentWithImageResources, SIGNAL(undoAvailable(bool)), q, QQuickTextEdit, SIGNAL(canUndoChanged()));
- qmlobject_connect(document, QQuickTextDocumentWithImageResources, SIGNAL(redoAvailable(bool)), q, QQuickTextEdit, SIGNAL(canRedoChanged()));
- qmlobject_connect(document, QQuickTextDocumentWithImageResources, SIGNAL(imagesLoaded()), q, QQuickTextEdit, SLOT(updateSize()));
- QObject::connect(document, &QQuickTextDocumentWithImageResources::contentsChange, q, &QQuickTextEdit::q_contentsChange);
+ qmlobject_connect(document, QTextDocument, SIGNAL(undoAvailable(bool)), q, QQuickTextEdit, SIGNAL(canUndoChanged()));
+ qmlobject_connect(document, QTextDocument, SIGNAL(redoAvailable(bool)), q, QQuickTextEdit, SIGNAL(canRedoChanged()));
+ QObject::connect(document, &QTextDocument::contentsChange, q, &QQuickTextEdit::q_contentsChange);
QObject::connect(document->documentLayout(), &QAbstractTextDocumentLayout::updateBlock, q, &QQuickTextEdit::invalidateBlock);
QObject::connect(control, &QQuickTextControl::linkHovered, q, &QQuickTextEdit::q_linkHovered);
QObject::connect(control, &QQuickTextControl::markerHovered, q, &QQuickTextEdit::q_markerHovered);
@@ -2485,10 +2839,12 @@ void QQuickTextEditPrivate::init()
document->setUndoRedoEnabled(false); // flush undo buffer.
document->setUndoRedoEnabled(true);
updateDefaultTextOption();
+ document->setModified(false); // we merely changed some defaults: no edits worth saving yet
q->updateSize();
#if QT_CONFIG(cursor)
updateMouseCursorShape();
#endif
+ setSizePolicy(QLayoutPolicy::Preferred, QLayoutPolicy::Preferred);
}
void QQuickTextEditPrivate::resetInputMethod()
@@ -2669,9 +3025,6 @@ void QQuickTextEdit::updateSize()
return;
}
- qreal naturalWidth = d->implicitWidth - leftPadding() - rightPadding();
-
- qreal newWidth = d->document->idealWidth();
// ### assumes that if the width is set, the text will fill to edges
// ### (unless wrap is false, then clipping will occur)
if (widthValid()) {
@@ -2683,8 +3036,7 @@ void QQuickTextEdit::updateSize()
}
if (d->requireImplicitWidth) {
d->document->setTextWidth(-1);
- naturalWidth = d->document->idealWidth();
-
+ const qreal naturalWidth = d->document->idealWidth();
const bool wasInLayout = d->inLayout;
d->inLayout = true;
if (d->isImplicitResizeEnabled())
@@ -2694,19 +3046,22 @@ void QQuickTextEdit::updateSize()
return; // get this far we'll get a warning to that effect.
}
const qreal newTextWidth = width() - leftPadding() - rightPadding();
- if (d->document->textWidth() != newTextWidth) {
+ if (d->document->textWidth() != newTextWidth)
+ d->document->setTextWidth(newTextWidth);
+ } else if (d->wrapMode == NoWrap) {
+ // normally, if explicit width is not set, we should call setTextWidth(-1) here,
+ // as we don't need to fit the text to any fixed width. But because of some bug
+ // in QTextDocument it also breaks RTL text alignment, so we use "idealWidth" instead.
+ const qreal newTextWidth = d->document->idealWidth();
+ if (d->document->textWidth() != newTextWidth)
d->document->setTextWidth(newTextWidth);
- newWidth = d->document->idealWidth();
- }
- //### need to confirm cost of always setting these
- } else if (d->wrapMode == NoWrap && d->document->textWidth() != newWidth) {
- d->document->setTextWidth(newWidth); // ### Text does not align if width is not set or the idealWidth exceeds the textWidth (QTextDoc bug)
} else {
d->document->setTextWidth(-1);
}
QFontMetricsF fm(d->font);
- qreal newHeight = d->document->isEmpty() ? qCeil(fm.height()) : d->document->size().height();
+ const qreal newHeight = d->document->isEmpty() ? qCeil(fm.height()) : d->document->size().height();
+ const qreal newWidth = d->document->idealWidth();
if (d->isImplicitResizeEnabled()) {
// ### Setting the implicitWidth triggers another updateSize(), and unless there are bindings nothing has changed.
@@ -2718,12 +3073,23 @@ void QQuickTextEdit::updateSize()
d->xoff = leftPadding() + qMax(qreal(0), QQuickTextUtil::alignedX(d->document->size().width(), width() - leftPadding() - rightPadding(), effectiveHAlign()));
d->yoff = topPadding() + QQuickTextUtil::alignedY(d->document->size().height(), height() - topPadding() - bottomPadding(), d->vAlign);
- setBaselineOffset(fm.ascent() + d->yoff + d->textMargin);
+
+ qreal baseline = fm.ascent();
+ QTextBlock firstBlock = d->document->firstBlock();
+ if (firstBlock.isValid() && firstBlock.layout() != nullptr && firstBlock.lineCount() > 0)
+ baseline = firstBlock.layout()->lineAt(0).ascent();
+
+ setBaselineOffset(baseline + d->yoff + d->textMargin);
QSizeF size(newWidth, newHeight);
if (d->contentSize != size) {
d->contentSize = size;
- emit contentSizeChanged();
+ // Note: inResize is a bitfield so QScopedValueRollback can't be used here
+ const bool wasInResize = d->inResize;
+ d->inResize = true;
+ if (!wasInResize)
+ emit contentSizeChanged();
+ d->inResize = wasInResize;
updateTotalLines();
}
}
@@ -2861,6 +3227,34 @@ void QQuickTextEditPrivate::updateDefaultTextOption()
}
}
+void QQuickTextEditPrivate::onDocumentStatusChanged()
+{
+ Q_ASSERT(quickDocument);
+ switch (quickDocument->status()) {
+ case QQuickTextDocument::Status::Loaded:
+ case QQuickTextDocument::Status::Saved:
+ switch (QQuickTextDocumentPrivate::get(quickDocument)->detectedFormat) {
+ case Qt::RichText:
+ richText = (format == QQuickTextEdit::RichText || format == QQuickTextEdit::AutoText);
+ markdownText = false;
+ break;
+ case Qt::MarkdownText:
+ richText = false;
+ markdownText = (format == QQuickTextEdit::MarkdownText || format == QQuickTextEdit::AutoText);
+ break;
+ case Qt::PlainText:
+ richText = false;
+ markdownText = false;
+ break;
+ case Qt::AutoText: // format not detected
+ break;
+ }
+ break;
+ default:
+ break;
+ }
+}
+
void QQuickTextEdit::focusInEvent(QFocusEvent *event)
{
Q_D(QQuickTextEdit);
@@ -2905,19 +3299,21 @@ void QQuickTextEditPrivate::handleFocusEvent(QFocusEvent *event)
}
}
-void QQuickTextEditPrivate::addCurrentTextNodeToRoot(QQuickTextNodeEngine *engine, QSGTransformNode *root, QQuickTextNode *node, TextNodeIterator &it, int startPos)
+void QQuickTextEditPrivate::addCurrentTextNodeToRoot(QQuickTextNodeEngine *engine, QSGTransformNode *root, QSGInternalTextNode *node, TextNodeIterator &it, int startPos)
{
engine->addToSceneGraph(node, QQuickText::Normal, QColor());
it = textNodeMap.insert(it, TextNode(startPos, node));
++it;
root->appendChildNode(node);
+ ++renderedBlockCount;
}
-QQuickTextNode *QQuickTextEditPrivate::createTextNode()
+QSGInternalTextNode *QQuickTextEditPrivate::createTextNode()
{
Q_Q(QQuickTextEdit);
- QQuickTextNode* node = new QQuickTextNode(q);
- node->setUseNativeRenderer(renderType == QQuickTextEdit::NativeRendering);
+ QSGInternalTextNode* node = sceneGraphContext()->createInternalTextNode(sceneGraphRenderContext());
+ node->setRenderType(QSGTextNode::RenderType(renderType));
+ node->setFiltering(q->smooth() ? QSGTexture::Linear : QSGTexture::Nearest);
return node;
}
@@ -3047,8 +3443,9 @@ void QQuickTextEdit::remove(int start, int end)
\since 5.1
Returns the QQuickTextDocument of this TextEdit.
- It can be used to implement syntax highlighting using
- \l QSyntaxHighlighter.
+ Since Qt 6.7, it has features for loading and saving files.
+ It can also be used in C++ as a means of accessing the underlying QTextDocument
+ instance, for example to install a \l QSyntaxHighlighter.
\sa QQuickTextDocument
*/
@@ -3056,8 +3453,11 @@ void QQuickTextEdit::remove(int start, int end)
QQuickTextDocument *QQuickTextEdit::textDocument()
{
Q_D(QQuickTextEdit);
- if (!d->quickDocument)
+ if (!d->quickDocument) {
d->quickDocument = new QQuickTextDocument(this);
+ connect(d->quickDocument, &QQuickTextDocument::statusChanged, d->quickDocument,
+ [d]() { d->onDocumentStatusChanged(); } );
+ }
return d->quickDocument;
}
@@ -3399,4 +3799,3 @@ QQuickPre64TextEdit::QQuickPre64TextEdit(QQuickItem *parent)
QT_END_NAMESPACE
#include "moc_qquicktextedit_p.cpp"
-