Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qlineedit.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include "qlineedit.h"
6#include "qlineedit_p.h"
7
8#if QT_CONFIG(action)
9# include "qaction.h"
10#endif
11#include "qapplication.h"
12#include "qclipboard.h"
13#if QT_CONFIG(draganddrop)
14#include <qdrag.h>
15#endif
16#include "qdrawutil.h"
17#include "qevent.h"
18#include "qfontmetrics.h"
19#include "qstylehints.h"
20#if QT_CONFIG(menu)
21#include "qmenu.h"
22#endif
23#include "qpainter.h"
24#include "qpixmap.h"
25#include "qpointer.h"
26#include "qstringlist.h"
27#include "qstyle.h"
28#include "qstyleoption.h"
29#include "qtimer.h"
30#include "qvalidator.h"
31#include "qvariant.h"
32#include "qdebug.h"
33#if QT_CONFIG(textedit)
34#include "qtextedit.h"
35#include <private/qtextedit_p.h>
36#endif
37#include <private/qwidgettextcontrol_p.h>
38
39#if QT_CONFIG(accessibility)
40#include "qaccessible.h"
41#endif
42#if QT_CONFIG(itemviews)
43#include "qabstractitemview.h"
44#endif
45#if QT_CONFIG(style_stylesheet)
46#include "private/qstylesheetstyle_p.h"
47#endif
48#if QT_CONFIG(shortcut)
49#include "private/qapplication_p.h"
50#include "private/qshortcutmap_p.h"
51#include "qkeysequence.h"
52#define ACCEL_KEY(k) (!QCoreApplication::testAttribute(Qt::AA_DontShowShortcutsInContextMenus)
53 && !QGuiApplicationPrivate::instance()->shortcutMap.hasShortcutForKeySequence(k) ?
54 u'\t' + QKeySequence(k).toString(QKeySequence::NativeText) : QString())
55#else
56#define ACCEL_KEY(k) QString()
57#endif
58
59#include <limits.h>
60#ifdef DrawText
61#undef DrawText
62#endif
63
65
66using namespace Qt::StringLiterals;
67
68/*!
69 Initialize \a option with the values from this QLineEdit. This method
70 is useful for subclasses when they need a QStyleOptionFrame, but don't want
71 to fill in all the information themselves.
72
73 \sa QStyleOption::initFrom()
74*/
75void QLineEdit::initStyleOption(QStyleOptionFrame *option) const
76{
77 if (!option)
78 return;
79
80 Q_D(const QLineEdit);
81 option->initFrom(this);
82 option->rect = contentsRect();
83 option->lineWidth = d->frame ? style()->pixelMetric(QStyle::PM_DefaultFrameWidth, option, this)
84 : 0;
85 option->midLineWidth = 0;
86 option->state |= QStyle::State_Sunken;
87 if (d->control->isReadOnly())
88 option->state |= QStyle::State_ReadOnly;
89#ifdef QT_KEYPAD_NAVIGATION
90 if (hasEditFocus())
91 option->state |= QStyle::State_HasEditFocus;
92#endif
93 option->features = QStyleOptionFrame::None;
94}
95
96/*!
97 \class QLineEdit
98 \brief The QLineEdit widget is a one-line text editor.
99
100 \ingroup basicwidgets
101 \inmodule QtWidgets
102
103 \image fusion-lineedit.png {Line edit showing a text greeting}
104
105 A line edit allows users to enter and edit a single line of
106 plain text with useful editing functions, including undo and redo, cut and
107 paste, and drag and drop.
108
109 By changing the echoMode() of a line edit, it can also be used as
110 a write-only field for inputs such as passwords.
111
112 QTextEdit is a related class that allows multi-line, rich text
113 editing.
114
115 \section1 Constraining Text
116
117 Use \l maxLength to define the maximum permitted length of a text. You can
118 use a \l inputMask and \l setValidator() to further constrain the text
119 content.
120
121 \section1 Editing Text
122
123 You can change the text with setText() or insert(). Use text() to retrieve
124 the text and displayText() to retrieve the displayed text (which may be
125 different, see \l{EchoMode}). You can select the text with setSelection() or
126 selectAll(), and you can cut(), copy(), and paste() the selection. To align
127 the text, use setAlignment().
128
129 When the text changes, the textChanged() signal is emitted. When the text
130 changes in some other way than by calling setText(), the textEdited() signal
131 is emitted. When the cursor is moved, the cursorPositionChanged() signal is
132 emitted. And when the Return or Enter key is selected, the returnPressed()
133 signal is emitted.
134
135 When text editing is finished, either because the line edit lost focus
136 or Return/Enter was selected, the editingFinished() signal is emitted.
137
138 If the line edit focus is lost without any text changes, the
139 editingFinished() signal won't be emitted.
140
141 If there is a validator set on the line edit, the
142 returnPressed()/editingFinished() signals will only be emitted if the
143 validator returns QValidator::Acceptable.
144
145 For more information on the many ways that QLineEdit can be used, see
146 \l {Line Edits Example}, which also provides a selection of line edit
147 examples that show the effects of various properties and validators on the
148 input and output supplied by the user.
149
150 \section1 Setting a Frame
151
152 By default, QLineEdits have a frame as specified in the platform
153 style guides. You can turn the frame off by calling setFrame(false).
154
155 \section1 Default Key Bindings
156
157 The table below describes the default key bindings.
158
159 \note The line edit also provides a context menu (usually invoked by a
160 right-click) that presents some of the editing options listed below.
161
162 \target desc
163 \table
164 \header \li Keystroke \li Action
165 \row \li Left Arrow \li Moves the cursor one character to the left.
166 \row \li Shift+Left Arrow \li Moves and selects text one character to the left.
167 \row \li Right Arrow \li Moves the cursor one character to the right.
168 \row \li Shift+Right Arrow \li Moves and selects text one character to the right.
169 \row \li Home \li Moves the cursor to the beginning of the line.
170 \row \li End \li Moves the cursor to the end of the line.
171 \row \li Backspace \li Deletes the character to the left of the cursor.
172 \row \li Ctrl+Backspace \li Deletes the word to the left of the cursor.
173 \row \li Delete \li Deletes the character to the right of the cursor.
174 \row \li Ctrl+Delete \li Deletes the word to the right of the cursor.
175 \row \li Ctrl+A \li Selects all.
176 \row \li Ctrl+C \li Copies the selected text to the clipboard.
177 \row \li Ctrl+Insert \li Copies the selected text to the clipboard.
178 \row \li Ctrl+K \li Deletes to the end of the line.
179 \row \li Ctrl+V \li Pastes the clipboard text into line edit.
180 \row \li Shift+Insert \li Pastes the clipboard text into line edit.
181 \row \li Ctrl+X \li Deletes the selected text and copies it to the clipboard.
182 \row \li Shift+Delete \li Deletes the selected text and copies it to the clipboard.
183 \row \li Ctrl+Z \li Undoes the last operation.
184 \row \li Ctrl+Y \li Redoes the last undone operation.
185 \endtable
186
187 Any other keystroke that represents a valid character, will cause the
188 character to be inserted into the line edit.
189
190 \sa QTextEdit, QLabel, QComboBox, {Line Edits Example}
191*/
192
193
194/*!
195 \fn void QLineEdit::textChanged(const QString &text)
196
197 This signal is emitted whenever the text changes. The \a text
198 argument is the new text.
199
200 Unlike textEdited(), this signal is also emitted when the text is
201 changed programmatically, for example, by calling setText().
202*/
203
204/*!
205 \fn void QLineEdit::textEdited(const QString &text)
206
207 This signal is emitted whenever the text is edited. The \a text
208 argument is the new text.
209
210 Unlike textChanged(), this signal is not emitted when the text is
211 changed programmatically, for example, by calling setText().
212*/
213
214/*!
215 \fn void QLineEdit::cursorPositionChanged(int oldPos, int newPos)
216
217 This signal is emitted whenever the cursor moves. The previous
218 position is given by \a oldPos, and the new position by \a newPos.
219
220 \sa setCursorPosition(), cursorPosition()
221*/
222
223/*!
224 \fn void QLineEdit::selectionChanged()
225
226 This signal is emitted whenever the selection changes.
227
228 \sa hasSelectedText(), selectedText()
229*/
230
231/*!
232 Constructs a line edit with no text.
233
234 The maximum text length is set to 32767 characters.
235
236 The \a parent argument is sent to the QWidget constructor.
237
238 \sa setText(), setMaxLength()
239*/
240QLineEdit::QLineEdit(QWidget* parent)
241 : QLineEdit(QString(), parent)
242{
243}
244
245/*!
246 Constructs a line edit containing the text \a contents as a child of
247 \a parent.
248
249 The cursor position is set to the end of the line and the maximum text
250 length to 32767 characters.
251
252 \sa text(), setMaxLength()
253*/
254QLineEdit::QLineEdit(const QString& contents, QWidget* parent)
255 : QWidget(*new QLineEditPrivate, parent, { })
256{
257 Q_D(QLineEdit);
258 d->init(contents);
259}
260
261
262
263/*!
264 Destroys the line edit.
265*/
266
267QLineEdit::~QLineEdit()
268{
269}
270
271
272/*!
273 \property QLineEdit::text
274 \brief The line edit's text.
275
276 Setting this property clears the selection, clears the undo/redo
277 history, moves the cursor to the end of the line, and resets the
278 \l modified property to false. The text is not validated when
279 inserted with setText().
280
281 The text is truncated to maxLength() length.
282
283 By default, this property contains an empty string.
284
285 \sa insert(), clear()
286*/
287QString QLineEdit::text() const
288{
289 Q_D(const QLineEdit);
290 return d->control->text();
291}
292
293void QLineEdit::setText(const QString& text)
294{
295 Q_D(QLineEdit);
296 d->setText(text);
297}
298
299/*!
300 \since 4.7
301
302 \property QLineEdit::placeholderText
303 \brief The line edit's placeholder text.
304
305 Setting this property makes the line edit display a grayed-out
306 placeholder text as long as the line edit is empty.
307
308 Normally, an empty line edit shows the placeholder text even
309 when it has focus. However, if the content is horizontally
310 centered, the placeholder text is not displayed under
311 the cursor when the line edit has focus.
312
313 By default, this property contains an empty string.
314
315 \sa text()
316*/
317QString QLineEdit::placeholderText() const
318{
319 Q_D(const QLineEdit);
320 return d->placeholderText;
321}
322
323void QLineEdit::setPlaceholderText(const QString& placeholderText)
324{
325 Q_D(QLineEdit);
326 if (d->placeholderText != placeholderText) {
327 d->placeholderText = placeholderText;
328 if (d->shouldShowPlaceholderText())
329 update();
330 }
331}
332
333/*!
334 \property QLineEdit::displayText
335 \brief The displayed text.
336
337 If \l echoMode is \l Normal, this returns the same as text(). If
338 \l EchoMode is \l Password or \l PasswordEchoOnEdit, it returns a string of
339 platform-dependent password mask characters (e.g. "******"). If \l EchoMode
340 is \l NoEcho, it returns an empty string.
341
342 By default, this property contains an empty string.
343
344 \sa setEchoMode(), text(), EchoMode
345*/
346
347QString QLineEdit::displayText() const
348{
349 Q_D(const QLineEdit);
350 return d->control->displayText();
351}
352
353
354/*!
355 \property QLineEdit::maxLength
356 \brief The maximum permitted length of the text.
357
358 If the text is too long, it is truncated at the limit.
359
360 If truncation occurs, any selected text will be unselected, the
361 cursor position is set to 0, and the first part of the string is
362 shown.
363
364 If the line edit has an input mask, the mask defines the maximum
365 string length.
366
367 By default, this property contains a value of 32767.
368
369 \sa inputMask
370*/
371
372int QLineEdit::maxLength() const
373{
374 Q_D(const QLineEdit);
375 return d->control->maxLength();
376}
377
378void QLineEdit::setMaxLength(int maxLength)
379{
380 Q_D(QLineEdit);
381 d->control->setMaxLength(maxLength);
382}
383
384/*!
385 \property QLineEdit::frame
386 \brief Whether the line edit draws itself with a frame.
387
388 If enabled (the default), the line edit draws itself inside a
389 frame. Otherwise, the line edit draws itself without any frame.
390*/
391bool QLineEdit::hasFrame() const
392{
393 Q_D(const QLineEdit);
394 return d->frame;
395}
396
397/*!
398 \enum QLineEdit::ActionPosition
399
400 This enum type describes how a line edit should display the action widgets to be
401 added.
402
403 \value LeadingPosition The widget is displayed to the left of the text
404 when using layout direction \c Qt::LeftToRight or to
405 the right when using \c Qt::RightToLeft, respectively.
406
407 \value TrailingPosition The widget is displayed to the right of the text
408 when using layout direction \c Qt::LeftToRight or to
409 the left when using \c Qt::RightToLeft, respectively.
410
411 \sa addAction(), removeAction(), QWidget::layoutDirection
412
413 \since 5.2
414*/
415
416#if QT_CONFIG(action)
417/*!
418 Adds the \a action to the list of actions at the \a position.
419
420 \since 5.2
421*/
422
423void QLineEdit::addAction(QAction *action, ActionPosition position)
424{
425 Q_D(QLineEdit);
426 QWidget::addAction(action);
427 d->addAction(action, nullptr, position);
428}
429
430/*!
431 \overload
432
433 Creates a new action with the given \a icon at the \a position.
434
435 \since 5.2
436*/
437
438QAction *QLineEdit::addAction(const QIcon &icon, ActionPosition position)
439{
440 QAction *result = new QAction(icon, QString(), this);
441 addAction(result, position);
442 return result;
443}
444#endif // QT_CONFIG(action)
445/*!
446 \property QLineEdit::clearButtonEnabled
447 \brief Whether the line edit displays a clear button when it is not empty.
448
449 If enabled, the line edit displays a trailing \uicontrol clear button when
450 it contains some text. Otherwise, the line edit does not show a
451 \uicontrol clear button (the default).
452
453 \sa addAction(), removeAction()
454 \since 5.2
455*/
456
457static const char clearButtonActionNameC[] = "_q_qlineeditclearaction";
458
459void QLineEdit::setClearButtonEnabled(bool enable)
460{
461#if QT_CONFIG(action)
462 Q_D(QLineEdit);
463 if (enable == isClearButtonEnabled())
464 return;
465 if (enable) {
466 QAction *clearAction = new QAction(d->clearButtonIcon(), QString(), this);
467 clearAction->setEnabled(!isReadOnly());
468 clearAction->setObjectName(QLatin1StringView(clearButtonActionNameC));
469
470 int flags = QLineEditPrivate::SideWidgetClearButton | QLineEditPrivate::SideWidgetFadeInWithText;
471 auto widgetAction = d->addAction(clearAction, nullptr, QLineEdit::TrailingPosition, flags);
472 widgetAction->setVisible(!text().isEmpty());
473 } else {
474 QAction *clearAction = findChild<QAction *>(QLatin1StringView(clearButtonActionNameC));
475 Q_ASSERT(clearAction);
476 d->removeAction(clearAction);
477 delete clearAction;
478 }
479#else
480 Q_UNUSED(enable);
481#endif // QT_CONFIG(action)
482}
483
484bool QLineEdit::isClearButtonEnabled() const
485{
486#if QT_CONFIG(action)
487 return findChild<QAction *>(QLatin1StringView(clearButtonActionNameC));
488#else
489 return false;
490#endif
491}
492
493void QLineEdit::setFrame(bool enable)
494{
495 Q_D(QLineEdit);
496 d->frame = enable;
497 update();
498 updateGeometry();
499}
500
501
502/*!
503 \enum QLineEdit::EchoMode
504
505 This enum type describes how a line edit should display its
506 contents.
507
508 \value Normal Display characters as they are entered. This is the
509 default.
510 \value NoEcho Do not display anything. This may be appropriate
511 for passwords where even the length of the
512 password should be kept secret.
513 \value Password Display platform-dependent password mask characters instead
514 of the characters actually entered.
515 \value PasswordEchoOnEdit Display characters only while they are entered.
516 Otherwise, display characters as with \c Password.
517
518 \sa setEchoMode(), echoMode()
519*/
520
521
522/*!
523 \property QLineEdit::echoMode
524 \brief The line edit's echo mode.
525
526 The echo mode determines how the text entered in the line edit is
527 displayed (or echoed) to the user.
528
529 The most common setting is \l Normal, in which the text entered by the
530 user is displayed verbatim. QLineEdit also supports modes that allow
531 the entered text to be suppressed or obscured: these include \l NoEcho,
532 \l Password and \l PasswordEchoOnEdit.
533
534 The widget's display and the ability to copy or drag the text is
535 affected by this setting.
536
537 By default, this property is set to \l Normal.
538
539 \sa EchoMode, displayText()
540*/
541
542QLineEdit::EchoMode QLineEdit::echoMode() const
543{
544 Q_D(const QLineEdit);
545 return (EchoMode) d->control->echoMode();
546}
547
548void QLineEdit::setEchoMode(EchoMode mode)
549{
550 Q_D(QLineEdit);
551 if (mode == (EchoMode)d->control->echoMode())
552 return;
553 Qt::InputMethodHints imHints = inputMethodHints();
554 imHints.setFlag(Qt::ImhHiddenText, mode == Password || mode == NoEcho);
555 imHints.setFlag(Qt::ImhNoAutoUppercase, mode != Normal);
556 imHints.setFlag(Qt::ImhNoPredictiveText, mode != Normal);
557 imHints.setFlag(Qt::ImhSensitiveData, mode != Normal);
558 setInputMethodHints(imHints);
559 d->control->setEchoMode(mode);
560 update();
561}
562
563
564#ifndef QT_NO_VALIDATOR
565/*!
566 Returns a pointer to the current input validator, or \nullptr if no
567 validator has been set.
568
569 \sa setValidator()
570*/
571
572const QValidator * QLineEdit::validator() const
573{
574 Q_D(const QLineEdit);
575 return d->control->validator();
576}
577
578/*!
579 Sets the validator for values of line edit to \a v.
580
581 The line edit's returnPressed() and editingFinished() signals will only
582 be emitted if \a v validates the line edit's content as \l{QValidator::}{Acceptable}.
583 The user may change the content to any \l{QValidator::}{Intermediate}
584 value during editing, but will be prevented from editing the text to a
585 value that \a v validates as \l{QValidator::}{Invalid}.
586
587 This allows you to constrain the text that will be stored when editing is
588 done while leaving users with enough freedom to edit the text from one valid
589 state to another.
590
591 To remove the current input validator, pass \c nullptr. The initial setting
592 is to have no input validator (any input is accepted up to maxLength()).
593
594 \sa validator(), hasAcceptableInput(), QIntValidator, QDoubleValidator,
595 QRegularExpressionValidator
596*/
597
598void QLineEdit::setValidator(const QValidator *v)
599{
600 Q_D(QLineEdit);
601 d->control->setValidator(v);
602}
603#endif // QT_NO_VALIDATOR
604
605#if QT_CONFIG(completer)
606/*!
607 \since 4.2
608
609 Sets this line edit to provide auto completions from the completer, \a c.
610 The completion mode is set using QCompleter::setCompletionMode().
611
612 To use a QCompleter with a QValidator or QLineEdit::inputMask, you need to
613 ensure that the model provided to QCompleter contains valid entries. You can
614 use the QSortFilterProxyModel to ensure that the QCompleter's model contains
615 only valid entries.
616
617 To remove the completer and disable auto-completion, pass a \c nullptr.
618
619 \sa QCompleter
620*/
621void QLineEdit::setCompleter(QCompleter *c)
622{
623 Q_D(QLineEdit);
624 if (c == d->control->completer())
625 return;
626 if (d->control->completer()) {
627 d->disconnectCompleter();
628 d->control->completer()->setWidget(nullptr);
629 if (d->control->completer()->parent() == this)
630 delete d->control->completer();
631 }
632 d->control->setCompleter(c);
633 if (!c)
634 return;
635 if (c->widget() == nullptr)
636 c->setWidget(this);
637 if (hasFocus())
638 d->connectCompleter();
639}
640
641/*!
642 \since 4.2
643
644 Returns the current QCompleter that provides completions.
645*/
646QCompleter *QLineEdit::completer() const
647{
648 Q_D(const QLineEdit);
649 return d->control->completer();
650}
651
652#endif // QT_CONFIG(completer)
653
654/*!
655 Returns a recommended size for the widget.
656
657 The width returned, in pixels, is usually enough for about 15 to
658 20 characters.
659*/
660
661QSize QLineEdit::sizeHint() const
662{
663 Q_D(const QLineEdit);
664 ensurePolished();
665 QFontMetrics fm(font());
666 const int iconSize = style()->pixelMetric(QStyle::PM_SmallIconSize, nullptr, this);
667 const QMargins tm = d->effectiveTextMargins();
668 int h = qMax(fm.height(), qMax(14, iconSize - 2)) + 2 * QLineEditPrivate::verticalMargin
669 + tm.top() + tm.bottom()
670 + d->topmargin + d->bottommargin;
671 int w = fm.horizontalAdvance(u'x') * 17 + 2 * QLineEditPrivate::horizontalMargin
672 + tm.left() + tm.right()
673 + d->leftmargin + d->rightmargin; // "some"
674 QStyleOptionFrame opt;
675 initStyleOption(&opt);
676 return style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h), this);
677}
678
679
680/*!
681 Returns a minimum size for the line edit.
682
683 The width returned is usually enough for at least one character.
684*/
685
686QSize QLineEdit::minimumSizeHint() const
687{
688 Q_D(const QLineEdit);
689 ensurePolished();
690 QFontMetrics fm = fontMetrics();
691 const QMargins tm = d->effectiveTextMargins();
692 int h = fm.height() + qMax(2 * QLineEditPrivate::verticalMargin, fm.leading())
693 + tm.top() + tm.bottom()
694 + d->topmargin + d->bottommargin;
695 int w = fm.maxWidth() + 2 * QLineEditPrivate::horizontalMargin
696 + tm.left() + tm.right()
697 + d->leftmargin + d->rightmargin;
698 QStyleOptionFrame opt;
699 initStyleOption(&opt);
700 return style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h), this);
701}
702
703
704/*!
705 \property QLineEdit::cursorPosition
706 \brief The current cursor position for this line edit.
707
708 Setting the cursor position causes a repaint when appropriate.
709
710 By default, this property contains a value of 0.
711*/
712
713int QLineEdit::cursorPosition() const
714{
715 Q_D(const QLineEdit);
716 return d->control->cursorPosition();
717}
718
719void QLineEdit::setCursorPosition(int pos)
720{
721 Q_D(QLineEdit);
722 d->control->setCursorPosition(pos);
723}
724
725// ### What should this do if the point is outside of contentsRect? Currently returns 0.
726/*!
727 Returns the cursor position under the point \a pos.
728*/
729int QLineEdit::cursorPositionAt(const QPoint &pos)
730{
731 Q_D(QLineEdit);
732 return d->xToPos(pos.x());
733}
734
735
736
737/*!
738 \property QLineEdit::alignment
739 \brief The alignment of the line edit.
740
741 Both horizontal and vertical alignment is allowed here, Qt::AlignJustify
742 will map to Qt::AlignLeft.
743
744 By default, this property contains a combination of Qt::AlignLeft and Qt::AlignVCenter.
745
746 \sa Qt::Alignment
747*/
748
749Qt::Alignment QLineEdit::alignment() const
750{
751 Q_D(const QLineEdit);
752 return QFlag(d->alignment);
753}
754
755void QLineEdit::setAlignment(Qt::Alignment alignment)
756{
757 Q_D(QLineEdit);
758 d->alignment = alignment;
759 update();
760}
761
762
763/*!
764 Moves the cursor forward \a steps characters. If \a mark is true,
765 each character moved over is added to the selection. If \a mark is
766 false, the selection is cleared.
767
768 \sa cursorBackward()
769*/
770
771void QLineEdit::cursorForward(bool mark, int steps)
772{
773 Q_D(QLineEdit);
774 d->control->cursorForward(mark, steps);
775}
776
777
778/*!
779 Moves the cursor back \a steps characters. If \a mark is true, each
780 character moved over is added to the selection. If \a mark is
781 false, the selection is cleared.
782
783 \sa cursorForward()
784*/
785void QLineEdit::cursorBackward(bool mark, int steps)
786{
787 cursorForward(mark, -steps);
788}
789
790/*!
791 Moves the cursor one word forward. If \a mark is true, the word is
792 also selected.
793
794 \sa cursorWordBackward()
795*/
796void QLineEdit::cursorWordForward(bool mark)
797{
798 Q_D(QLineEdit);
799 d->control->cursorWordForward(mark);
800}
801
802/*!
803 Moves the cursor one word backward. If \a mark is true, the word
804 is also selected.
805
806 \sa cursorWordForward()
807*/
808
809void QLineEdit::cursorWordBackward(bool mark)
810{
811 Q_D(QLineEdit);
812 d->control->cursorWordBackward(mark);
813}
814
815
816/*!
817 If no text is selected, deletes the character to the left of the
818 text cursor, and moves the cursor one position to the left. If any
819 text is selected, the cursor is moved to the beginning of the
820 selected text, and the selected text is deleted.
821
822 \sa del()
823*/
824void QLineEdit::backspace()
825{
826 Q_D(QLineEdit);
827 d->control->backspace();
828}
829
830/*!
831 If no text is selected, deletes the character to the right of the
832 text cursor. If any text is selected, the cursor is moved to the
833 beginning of the selected text, and the selected text is deleted.
834
835 \sa backspace()
836*/
837
838void QLineEdit::del()
839{
840 Q_D(QLineEdit);
841 d->control->del();
842}
843
844/*!
845 Moves the text cursor to the beginning of the line unless it is
846 already there. If \a mark is true, text is selected towards the
847 first position. Otherwise, any selected text is unselected if the
848 cursor is moved.
849
850 \sa end()
851*/
852
853void QLineEdit::home(bool mark)
854{
855 Q_D(QLineEdit);
856 d->control->home(mark);
857}
858
859/*!
860 Moves the text cursor to the end of the line unless it is already
861 there. If \a mark is true, text is selected towards the last
862 position. Otherwise, any selected text is unselected if the cursor
863 is moved.
864
865 \sa home()
866*/
867
868void QLineEdit::end(bool mark)
869{
870 Q_D(QLineEdit);
871 d->control->end(mark);
872}
873
874
875/*!
876 \property QLineEdit::modified
877 \brief Whether the line edit's contents has been modified by the user.
878
879 The modified flag is never read by QLineEdit; it has a default value
880 of false and is changed to true whenever the user changes the line
881 edit's contents.
882
883 This is useful for things that need to provide a default value but
884 do not start out knowing what the default should be (for example, it
885 depends on other fields on the form). Start the line edit without
886 the best default, and when the default is known, if modified()
887 returns \c false (the user hasn't entered any text), insert the
888 default value.
889
890 Calling setText() resets the modified flag to false.
891*/
892
893bool QLineEdit::isModified() const
894{
895 Q_D(const QLineEdit);
896 return d->control->isModified();
897}
898
899void QLineEdit::setModified(bool modified)
900{
901 Q_D(QLineEdit);
902 d->control->setModified(modified);
903}
904
905/*!
906 \property QLineEdit::hasSelectedText
907 \brief Whether there is any text selected.
908
909 hasSelectedText() returns \c true if some or all of the text has been
910 selected by the user. Otherwise, it returns \c false.
911
912 By default, this property is \c false.
913
914 \sa selectedText()
915*/
916
917
918bool QLineEdit::hasSelectedText() const
919{
920 Q_D(const QLineEdit);
921 return d->control->hasSelectedText();
922}
923
924/*!
925 \property QLineEdit::selectedText
926 \brief The selected text.
927
928 If there is no selected text, this property's value is
929 an empty string.
930
931 By default, this property contains an empty string.
932
933 \sa hasSelectedText()
934*/
935
936QString QLineEdit::selectedText() const
937{
938 Q_D(const QLineEdit);
939 return d->control->selectedText();
940}
941
942/*!
943 Returns the index of the first selected character in the
944 line edit (or -1 if no text is selected).
945
946 \sa selectedText()
947 \sa selectionEnd()
948 \sa selectionLength()
949*/
950
951int QLineEdit::selectionStart() const
952{
953 Q_D(const QLineEdit);
954 return d->control->selectionStart();
955}
956
957/*!
958 Returns the index of the character directly after the selection
959 in the line edit (or -1 if no text is selected).
960 \since 5.10
961
962 \sa selectedText()
963 \sa selectionStart()
964 \sa selectionLength()
965*/
966int QLineEdit::selectionEnd() const
967{
968 Q_D(const QLineEdit);
969 return d->control->selectionEnd();
970}
971
972/*!
973 Returns the length of the selection.
974 \since 5.10
975
976 \sa selectedText()
977 \sa selectionStart()
978 \sa selectionEnd()
979*/
980int QLineEdit::selectionLength() const
981{
982 return selectionEnd() - selectionStart();
983}
984
985/*!
986 Selects text from position \a start and for \a length characters.
987 Negative lengths are allowed.
988
989 \sa deselect(), selectAll(), selectedText()
990*/
991
992void QLineEdit::setSelection(int start, int length)
993{
994 Q_D(QLineEdit);
995 if (Q_UNLIKELY(start < 0 || start > (int)d->control->end())) {
996 qWarning("QLineEdit::setSelection: Invalid start position (%d)", start);
997 return;
998 }
999
1000 d->control->setSelection(start, length);
1001
1002 if (d->control->hasSelectedText()){
1003 QStyleOptionFrame opt;
1004 initStyleOption(&opt);
1005 if (!style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected, &opt, this))
1006 d->setCursorVisible(false);
1007 }
1008}
1009
1010
1011/*!
1012 \property QLineEdit::undoAvailable
1013 \brief Whether undo is available.
1014
1015 Undo becomes available once the user has modified the text in the line edit.
1016
1017 By default, this property is \c false.
1018*/
1019
1020bool QLineEdit::isUndoAvailable() const
1021{
1022 Q_D(const QLineEdit);
1023 return d->control->isUndoAvailable();
1024}
1025
1026/*!
1027 \property QLineEdit::redoAvailable
1028 \brief Whether redo is available.
1029
1030 Redo becomes available once the user has performed one or more undo operations
1031 on the text in the line edit.
1032
1033 By default, this property is \c false.
1034*/
1035
1036bool QLineEdit::isRedoAvailable() const
1037{
1038 Q_D(const QLineEdit);
1039 return d->control->isRedoAvailable();
1040}
1041
1042/*!
1043 \property QLineEdit::dragEnabled
1044 \brief Whether the line edit starts a drag if the user presses and
1045 moves the mouse on some selected text.
1046
1047 Dragging is disabled by default.
1048*/
1049
1050bool QLineEdit::dragEnabled() const
1051{
1052 Q_D(const QLineEdit);
1053 return d->dragEnabled;
1054}
1055
1056void QLineEdit::setDragEnabled(bool b)
1057{
1058 Q_D(QLineEdit);
1059 d->dragEnabled = b;
1060}
1061
1062/*!
1063 \property QLineEdit::cursorMoveStyle
1064 \brief The movement style of the cursor in this line edit.
1065 \since 4.8
1066
1067 When this property is set to Qt::VisualMoveStyle, the line edit will use a
1068 visual movement style. Using the left arrow key will always cause the
1069 cursor to move left, regardless of the text's writing direction. The same
1070 behavior applies to the right arrow key.
1071
1072 When the property is set to Qt::LogicalMoveStyle (the default), within a
1073 left-to-right (LTR) text block, using the left arrow key will increase
1074 the cursor position, whereas using the right arrow key will decrease the
1075 cursor position. If the text block is right-to-left (RTL), the opposite
1076 behavior applies.
1077*/
1078
1079Qt::CursorMoveStyle QLineEdit::cursorMoveStyle() const
1080{
1081 Q_D(const QLineEdit);
1082 return d->control->cursorMoveStyle();
1083}
1084
1085void QLineEdit::setCursorMoveStyle(Qt::CursorMoveStyle style)
1086{
1087 Q_D(QLineEdit);
1088 d->control->setCursorMoveStyle(style);
1089}
1090
1091/*!
1092 \property QLineEdit::acceptableInput
1093 \brief Whether the input satisfies the inputMask and the
1094 validator.
1095
1096 By default, this property is \c true.
1097
1098 \sa setInputMask(), setValidator()
1099*/
1100bool QLineEdit::hasAcceptableInput() const
1101{
1102 Q_D(const QLineEdit);
1103 return d->control->hasAcceptableInput();
1104}
1105
1106/*!
1107 \since 4.5
1108 Sets the margins around the text inside the frame to have the
1109 sizes \a left, \a top, \a right, and \a bottom.
1110
1111 \sa textMargins()
1112*/
1113void QLineEdit::setTextMargins(int left, int top, int right, int bottom)
1114{
1115 setTextMargins({left, top, right, bottom});
1116}
1117
1118/*!
1119 \since 4.6
1120 Sets the \a margins around the text inside the frame.
1121
1122 \sa textMargins()
1123*/
1124void QLineEdit::setTextMargins(const QMargins &margins)
1125{
1126 Q_D(QLineEdit);
1127 d->textMargins = margins;
1128 updateGeometry();
1129 update();
1130}
1131
1132/*!
1133 \since 4.6
1134 Returns the widget's text margins.
1135
1136 \sa setTextMargins()
1137*/
1138QMargins QLineEdit::textMargins() const
1139{
1140 Q_D(const QLineEdit);
1141 return d->textMargins;
1142}
1143
1144/*!
1145 \property QLineEdit::inputMask
1146 \brief The validation input mask.
1147
1148 Sets the QLineEdit's validation mask. Validators can be used
1149 instead of, or in conjunction with masks; see setValidator(). The default is
1150 an empty string, which means that no input mask is used.
1151
1152 To unset the mask and return to normal QLineEdit operation, pass an empty
1153 string.
1154
1155 The input mask is an input template string. It can contain the following
1156 elements:
1157 \table
1158 \row \li Mask Characters \li Defines the \l {QChar::} {Category} of input
1159 characters that are considered valid in this position.
1160 \row \li Meta Characters \li Various special meanings (see details below).
1161 \row \li Separators \li All other characters are regarded as immutable
1162 separators.
1163 \endtable
1164
1165 The following table shows the mask and meta characters that can be used in
1166 an input mask.
1167
1168 \table
1169 \header \li Mask Character \li Meaning
1170 \row \li \c A \li Character of the Letter category required, such as A-Z,
1171 a-z.
1172 \row \li \c a \li Character of the Letter category permitted but not
1173 required.
1174 \row \li \c N \li Character of the Letter or Number category required, such
1175 as A-Z, a-z, 0-9.
1176 \row \li \c n \li Character of the Letter or Number category permitted but
1177 not required.
1178 \row \li \c X \li Any non-blank character required.
1179 \row \li \c x \li Any non-blank character permitted but not required.
1180 \row \li \c 9 \li Character of the Number category required, such as 0-9.
1181 \row \li \c 0 \li Character of the Number category permitted but not
1182 required.
1183 \row \li \c D \li Character of the Number category and larger than zero
1184 required, such as 1-9.
1185 \row \li \c d \li Character of the Number category and larger than zero
1186 permitted but not required, such as 1-9.
1187 \row \li \c # \li Character of the Number category, or plus/minus sign
1188 permitted but not required.
1189 \row \li \c H \li Hexadecimal character required. A-F, a-f, 0-9.
1190 \row \li \c h \li Hexadecimal character permitted but not required.
1191 \row \li \c B \li Binary character required. 0-1.
1192 \row \li \c b \li Binary character permitted but not required.
1193 \header \li Meta Character \li Meaning
1194 \row \li \c > \li All following alphabetic characters are uppercased.
1195 \row \li \c < \li All following alphabetic characters are lowercased.
1196 \row \li \c ! \li Switch off case conversion.
1197 \row \li \c {;c} \li Terminates the input mask and sets the \e{blank}
1198 character to \e{c}.
1199 \row \li \c {[ ] { }} \li Reserved.
1200 \row \li \tt{\\} \li Use \tt{\\} to escape the special characters listed
1201 above to use them as separators.
1202 \endtable
1203
1204 When created or cleared, the line edit will be filled with a copy of the
1205 input mask string where the meta characters have been removed, and the mask
1206 characters have been replaced with the \e{blank} character (by default, a
1207 \c space).
1208
1209 When an input mask is set, the text() method returns a modified copy of the
1210 line edit content where all the \e{blank} characters have been removed. The
1211 unmodified content can be read using displayText().
1212
1213 The hasAcceptableInput() method returns false if the current content of the
1214 line edit does not fulfill the requirements of the input mask.
1215
1216 Examples:
1217 \table
1218 \header \li Mask \li Notes
1219 \row \li \c 000.000.000.000;_ \li IP address; blanks are \c{_}.
1220 \row \li \c HH:HH:HH:HH:HH:HH;_ \li MAC address
1221 \row \li \c 0000-00-00 \li ISO Date; blanks are \c space
1222 \row \li \c >AAAAA-AAAAA-AAAAA-AAAAA-AAAAA;# \li License number;
1223 blanks are \c{#} and all (alphabetic) characters are converted to
1224 uppercase.
1225 \endtable
1226
1227 To get range control (e.g., for an IP address) use masks together
1228 with \l{setValidator()}{validators}.
1229
1230 \sa maxLength, QChar::isLetter(), QChar::isNumber(), QChar::digitValue()
1231*/
1232QString QLineEdit::inputMask() const
1233{
1234 Q_D(const QLineEdit);
1235 return d->control->inputMask();
1236}
1237
1238void QLineEdit::setInputMask(const QString &inputMask)
1239{
1240 Q_D(QLineEdit);
1241 d->control->setInputMask(inputMask);
1242}
1243
1244/*!
1245 Selects all the text (highlights it) and moves the cursor to
1246 the end.
1247
1248 \note This is useful when a default value has been inserted
1249 because if the user types before clicking on the widget, the
1250 selected text will be deleted.
1251
1252 \sa setSelection(), deselect()
1253*/
1254
1255void QLineEdit::selectAll()
1256{
1257 Q_D(QLineEdit);
1258 d->control->selectAll();
1259}
1260
1261/*!
1262 Deselects any selected text.
1263
1264 \sa setSelection(), selectAll()
1265*/
1266
1267void QLineEdit::deselect()
1268{
1269 Q_D(QLineEdit);
1270 d->control->deselect();
1271}
1272
1273
1274/*!
1275 Deletes any selected text, inserts \a newText, and validates the
1276 result. If it is valid, it sets the new text as the new contents of the line
1277 edit.
1278
1279 \sa setText(), clear()
1280*/
1281void QLineEdit::insert(const QString &newText)
1282{
1283// q->resetInputContext(); //#### FIX ME IN QT
1284 Q_D(QLineEdit);
1285 d->control->insert(newText);
1286}
1287
1288/*!
1289 Clears the contents of the line edit.
1290
1291 \sa setText(), insert()
1292*/
1293void QLineEdit::clear()
1294{
1295 Q_D(QLineEdit);
1296 d->resetInputMethod();
1297 d->control->clear();
1298}
1299
1300/*!
1301 Undoes the last operation if undo is \l{QLineEdit::undoAvailable}{available}. Deselects any current
1302 selection, and updates the selection start to the current cursor
1303 position.
1304*/
1305void QLineEdit::undo()
1306{
1307 Q_D(QLineEdit);
1308 d->resetInputMethod();
1309 d->control->undo();
1310}
1311
1312/*!
1313 Redoes the last operation if redo is \l{QLineEdit::redoAvailable}{available}.
1314*/
1315void QLineEdit::redo()
1316{
1317 Q_D(QLineEdit);
1318 d->resetInputMethod();
1319 d->control->redo();
1320}
1321
1322
1323/*!
1324 \property QLineEdit::readOnly
1325 \brief Whether the line edit is read-only.
1326
1327 In read-only mode, the user can still copy the text to the
1328 clipboard, or drag and drop the text (if echoMode() is \l Normal),
1329 but cannot edit it.
1330
1331 QLineEdit does not show a cursor in read-only mode.
1332
1333 By default, this property is \c false.
1334
1335 \sa setEnabled()
1336*/
1337
1338bool QLineEdit::isReadOnly() const
1339{
1340 Q_D(const QLineEdit);
1341 return d->control->isReadOnly();
1342}
1343
1344void QLineEdit::setReadOnly(bool enable)
1345{
1346 Q_D(QLineEdit);
1347 if (d->control->isReadOnly() != enable) {
1348 d->control->setReadOnly(enable);
1349 d->setClearButtonEnabled(!enable);
1350 setAttribute(Qt::WA_MacShowFocusRect, !enable);
1351 setAttribute(Qt::WA_InputMethodEnabled, d->shouldEnableInputMethod());
1352#ifndef QT_NO_CURSOR
1353 setCursor(enable ? Qt::ArrowCursor : Qt::IBeamCursor);
1354#endif
1355 QEvent event(QEvent::ReadOnlyChange);
1356 QCoreApplication::sendEvent(this, &event);
1357 update();
1358#if QT_CONFIG(accessibility)
1359 QAccessible::State changedState;
1360 changedState.readOnly = true;
1361 QAccessibleStateChangeEvent ev(this, changedState);
1362 QAccessible::updateAccessibility(&ev);
1363#endif
1364 }
1365}
1366
1367
1368#ifndef QT_NO_CLIPBOARD
1369/*!
1370 Copies the selected text to the clipboard and deletes it, if there
1371 is any, and if echoMode() is \l Normal.
1372
1373 If the current validator disallows deleting the selected text,
1374 cut() will copy without deleting.
1375
1376 \sa copy(), paste(), setValidator()
1377*/
1378
1379void QLineEdit::cut()
1380{
1381 if (hasSelectedText()) {
1382 copy();
1383 del();
1384 }
1385}
1386
1387
1388/*!
1389 Copies the selected text to the clipboard, if there is any, and if
1390 echoMode() is \l Normal.
1391
1392 \sa cut(), paste()
1393*/
1394
1395void QLineEdit::copy() const
1396{
1397 Q_D(const QLineEdit);
1398 d->control->copy();
1399}
1400
1401/*!
1402 Inserts the clipboard's text at the cursor position, deleting any
1403 selected text, providing the line edit is not \l{QLineEdit::readOnly}{read-only}.
1404
1405 If the end result would be invalid to the current
1406 \l{setValidator()}{validator}, nothing happens.
1407
1408 \sa copy(), cut()
1409*/
1410
1411void QLineEdit::paste()
1412{
1413 Q_D(QLineEdit);
1414 d->control->paste();
1415}
1416
1417#endif // !QT_NO_CLIPBOARD
1418
1419/*!
1420 \reimp
1421*/
1422void QLineEdit::timerEvent(QTimerEvent *e)
1423{
1424 Q_D(QLineEdit);
1425 int timerId = ((QTimerEvent*)e)->timerId();
1426 if (false) {
1427#if QT_CONFIG(draganddrop)
1428 } else if (timerId == d->dndTimer.timerId()) {
1429 d->drag();
1430#endif
1431 }
1432 else if (timerId == d->tripleClickTimer.timerId())
1433 d->tripleClickTimer.stop();
1434}
1435
1436/*! \reimp
1437*/
1438bool QLineEdit::event(QEvent * e)
1439{
1440 Q_D(QLineEdit);
1441 if (e->type() == QEvent::ContextMenu) {
1442#ifndef QT_NO_IM
1443 if (d->control->composeMode())
1444 return true;
1445#endif
1446 //d->separate();
1447 } else if (e->type() == QEvent::WindowActivate) {
1448 QTimer::singleShot(0, this, [this]() {
1449 Q_D(QLineEdit);
1450 d->handleWindowActivate();
1451 });
1452#ifndef QT_NO_SHORTCUT
1453 } else if (e->type() == QEvent::ShortcutOverride) {
1454 QKeyEvent *ke = static_cast<QKeyEvent*>(e);
1455 d->control->processShortcutOverrideEvent(ke);
1456#endif
1457 } else if (e->type() == QEvent::Show) {
1458 //In order to get the cursor blinking if QComboBox::setEditable is called when the combobox has focus
1459 if (hasFocus()) {
1460 d->control->setBlinkingCursorEnabled(true);
1461 QStyleOptionFrame opt;
1462 initStyleOption(&opt);
1463 if ((!hasSelectedText() && d->control->preeditAreaText().isEmpty())
1464 || style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected, &opt, this))
1465 d->setCursorVisible(true);
1466 }
1467 } else if (e->type() == QEvent::Hide) {
1468 d->control->setBlinkingCursorEnabled(false);
1469#if QT_CONFIG(action)
1470 } else if (e->type() == QEvent::ActionRemoved) {
1471 d->removeAction(static_cast<QActionEvent *>(e)->action());
1472#endif
1473 } else if (e->type() == QEvent::Resize) {
1474 d->positionSideWidgets();
1475 } else if (e->type() == QEvent::StyleChange) {
1476 d->initMouseYThreshold();
1477 }
1478#ifdef QT_KEYPAD_NAVIGATION
1479 if (QApplicationPrivate::keypadNavigationEnabled()) {
1480 if (e->type() == QEvent::EnterEditFocus) {
1481 end(false);
1482 d->setCursorVisible(true);
1483 d->control->setCursorBlinkEnabled(true);
1484 } else if (e->type() == QEvent::LeaveEditFocus) {
1485 d->setCursorVisible(false);
1486 d->control->setCursorBlinkEnabled(false);
1487 if (d->edited && (d->control->hasAcceptableInput()
1488 || d->control->fixup())) {
1489 emit editingFinished();
1490 d->edited = false;
1491 }
1492 }
1493 }
1494#endif
1495 return QWidget::event(e);
1496}
1497
1498/*! \reimp
1499*/
1500void QLineEdit::mousePressEvent(QMouseEvent* e)
1501{
1502 Q_D(QLineEdit);
1503
1504 d->mousePressPos = e->position().toPoint();
1505
1506 if (d->sendMouseEventToInputContext(e))
1507 return;
1508 if (e->button() == Qt::RightButton) {
1509 e->ignore();
1510 return;
1511 }
1512#ifdef QT_KEYPAD_NAVIGATION
1513 if (QApplication::QApplicationPrivate() && !hasEditFocus()) {
1514 setEditFocus(true);
1515 // Get the completion list to pop up.
1516 if (d->control->completer())
1517 d->control->completer()->complete();
1518 }
1519#endif
1520 if (d->tripleClickTimer.isActive() && (e->position().toPoint() - d->tripleClick).manhattanLength() <
1521 QApplication::startDragDistance()) {
1522 selectAll();
1523 return;
1524 }
1525 bool mark = e->modifiers() & Qt::ShiftModifier;
1526#ifdef Q_OS_ANDROID
1527 mark = mark && (d->imHints & Qt::ImhNoPredictiveText);
1528#endif // Q_OS_ANDROID
1529 int cursor = d->xToPos(e->position().toPoint().x());
1530#if QT_CONFIG(draganddrop)
1531 if (!mark && d->dragEnabled && d->control->echoMode() == Normal &&
1532 e->button() == Qt::LeftButton && d->inSelection(e->position().toPoint().x())) {
1533 if (!d->dndTimer.isActive())
1534 d->dndTimer.start(QApplication::startDragTime(), this);
1535 } else
1536#endif
1537 {
1538 d->control->moveCursor(cursor, mark);
1539 }
1540}
1541
1542/*! \reimp
1543*/
1544void QLineEdit::mouseMoveEvent(QMouseEvent * e)
1545{
1546 Q_D(QLineEdit);
1547
1548 if (e->buttons() & Qt::LeftButton) {
1549#if QT_CONFIG(draganddrop)
1550 if (d->dndTimer.isActive()) {
1551 if ((d->mousePressPos - e->position().toPoint()).manhattanLength() > QApplication::startDragDistance())
1552 d->drag();
1553 } else
1554#endif
1555 {
1556#ifndef Q_OS_ANDROID
1557 const bool select = true;
1558#else
1559 const bool select = (d->imHints & Qt::ImhNoPredictiveText);
1560#endif
1561#ifndef QT_NO_IM
1562 if (d->mouseYThreshold > 0 && e->position().toPoint().y() > d->mousePressPos.y() + d->mouseYThreshold) {
1563 if (layoutDirection() == Qt::RightToLeft)
1564 d->control->home(select);
1565 else
1566 d->control->end(select);
1567 } else if (d->mouseYThreshold > 0 && e->position().toPoint().y() + d->mouseYThreshold < d->mousePressPos.y()) {
1568 if (layoutDirection() == Qt::RightToLeft)
1569 d->control->end(select);
1570 else
1571 d->control->home(select);
1572 } else if (d->control->composeMode() && select) {
1573 int startPos = d->xToPos(d->mousePressPos.x());
1574 int currentPos = d->xToPos(e->position().toPoint().x());
1575 if (startPos != currentPos)
1576 d->control->setSelection(startPos, currentPos - startPos);
1577
1578 } else
1579#endif
1580 {
1581 d->control->moveCursor(d->xToPos(e->position().toPoint().x()), select);
1582 }
1583 }
1584 }
1585
1586 d->sendMouseEventToInputContext(e);
1587}
1588
1589/*! \reimp
1590*/
1591void QLineEdit::mouseReleaseEvent(QMouseEvent* e)
1592{
1593 Q_D(QLineEdit);
1594 if (d->sendMouseEventToInputContext(e))
1595 return;
1596#if QT_CONFIG(draganddrop)
1597 if (e->button() == Qt::LeftButton) {
1598 if (d->dndTimer.isActive()) {
1599 d->dndTimer.stop();
1600 deselect();
1601 return;
1602 }
1603 }
1604#endif
1605#ifndef QT_NO_CLIPBOARD
1606 if (QGuiApplication::clipboard()->supportsSelection()) {
1607 if (e->button() == Qt::LeftButton) {
1608 d->control->copy(QClipboard::Selection);
1609 } else if (!d->control->isReadOnly() && e->button() == Qt::MiddleButton) {
1610 deselect();
1611 d->control->paste(QClipboard::Selection);
1612 }
1613 }
1614#endif
1615
1616 if (!isReadOnly() && rect().contains(e->position().toPoint()))
1617 d->handleSoftwareInputPanel(e->button(), d->clickCausedFocus);
1618 d->clickCausedFocus = 0;
1619}
1620
1621/*! \reimp
1622*/
1623void QLineEdit::mouseDoubleClickEvent(QMouseEvent* e)
1624{
1625 Q_D(QLineEdit);
1626
1627 if (e->button() == Qt::LeftButton) {
1628 int position = d->xToPos(e->position().toPoint().x());
1629
1630 // exit composition mode
1631#ifndef QT_NO_IM
1632 if (d->control->composeMode()) {
1633 int preeditPos = d->control->cursor();
1634 int posInPreedit = position - d->control->cursor();
1635 int preeditLength = d->control->preeditAreaText().size();
1636 bool positionOnPreedit = false;
1637
1638 if (posInPreedit >= 0 && posInPreedit <= preeditLength)
1639 positionOnPreedit = true;
1640
1641 int textLength = d->control->end();
1642 d->control->commitPreedit();
1643 int sizeChange = d->control->end() - textLength;
1644
1645 if (positionOnPreedit) {
1646 if (sizeChange == 0)
1647 position = -1; // cancel selection, word disappeared
1648 else
1649 // ensure not selecting after preedit if event happened there
1650 position = qBound(preeditPos, position, preeditPos + sizeChange);
1651 } else if (position > preeditPos) {
1652 // adjust positions after former preedit by how much text changed
1653 position += (sizeChange - preeditLength);
1654 }
1655 }
1656#endif
1657
1658 if (position >= 0)
1659 d->control->selectWordAtPos(position);
1660
1661 d->tripleClickTimer.start(QApplication::doubleClickInterval(), this);
1662 d->tripleClick = e->position().toPoint();
1663 } else {
1664 d->sendMouseEventToInputContext(e);
1665 }
1666}
1667
1668/*!
1669 \fn void QLineEdit::returnPressed()
1670
1671 This signal is emitted when the Return or Enter key is used.
1672
1673 \note If there is a validator() or inputMask() set on the line
1674 edit, the returnPressed() signal will only be emitted if the input
1675 follows the inputMask() and the validator() returns
1676 QValidator::Acceptable.
1677*/
1678
1679/*!
1680 \fn void QLineEdit::editingFinished()
1681
1682 This signal is emitted when the Return or Enter key is used, or if the line
1683 edit loses focus and its contents have changed since the last time this
1684 signal was emitted.
1685
1686 \note If there is a validator() or inputMask() set on the line edit and
1687 enter/return is used, the editingFinished() signal will only be emitted
1688 if the input follows the inputMask() and the validator() returns
1689 QValidator::Acceptable.
1690*/
1691
1692/*!
1693 \fn void QLineEdit::inputRejected()
1694 \since 5.12
1695
1696 This signal is emitted when the user uses a key that is not
1697 considered to be valid input. For example, if using a key results in a
1698 validator's \l {QValidator::validate()}{validate()} call to return
1699 \l {QValidator::Invalid}{Invalid}. Another case is when trying
1700 to enter more characters beyond the maximum length of the line edit.
1701
1702 \note This signal will still be emitted when only a part of the text is
1703 accepted. For example, if there is a maximum length set and the clipboard
1704 text is longer than the maximum length when it is pasted.
1705*/
1706
1707/*!
1708 Converts the given key press \a event into a line edit action.
1709
1710 If Return or Enter is used and the current text is valid (or
1711 can be \l{QValidator::fixup()}{made valid} by the
1712 validator), the signal returnPressed() is emitted.
1713
1714 \sa {Default Key Bindings}
1715*/
1716
1717void QLineEdit::keyPressEvent(QKeyEvent *event)
1718{
1719 Q_D(QLineEdit);
1720 #ifdef QT_KEYPAD_NAVIGATION
1721 bool select = false;
1722 switch (event->key()) {
1723 case Qt::Key_Select:
1724 if (QApplicationPrivate::keypadNavigationEnabled()) {
1725 if (hasEditFocus()) {
1726 setEditFocus(false);
1727 if (d->control->completer() && d->control->completer()->popup()->isVisible())
1728 d->control->completer()->popup()->hide();
1729 select = true;
1730 }
1731 }
1732 break;
1733 case Qt::Key_Back:
1734 case Qt::Key_No:
1735 if (!QApplicationPrivate::keypadNavigationEnabled() || !hasEditFocus()) {
1736 event->ignore();
1737 return;
1738 }
1739 break;
1740 default:
1741 if (QApplicationPrivate::keypadNavigationEnabled()) {
1742 if (!hasEditFocus() && !(event->modifiers() & Qt::ControlModifier)) {
1743 if (!event->text().isEmpty() && event->text().at(0).isPrint()
1744 && !isReadOnly())
1745 setEditFocus(true);
1746 else {
1747 event->ignore();
1748 return;
1749 }
1750 }
1751 }
1752 }
1753
1754
1755
1756 if (QApplicationPrivate::keypadNavigationEnabled() && !select && !hasEditFocus()) {
1757 setEditFocus(true);
1758 if (event->key() == Qt::Key_Select)
1759 return; // Just start. No action.
1760 }
1761#endif
1762 d->control->processKeyEvent(event);
1763 if (event->isAccepted())
1764 d->control->updateCursorBlinking();
1765}
1766
1767/*!
1768 \reimp
1769*/
1770void QLineEdit::keyReleaseEvent(QKeyEvent *e)
1771{
1772 Q_D(QLineEdit);
1773 if (!isReadOnly())
1774 d->handleSoftwareInputPanel();
1775 d->control->updateCursorBlinking();
1776 QWidget::keyReleaseEvent(e);
1777}
1778
1779/*!
1780 \since 4.4
1781
1782 Returns a rectangle that includes the line edit cursor.
1783*/
1784QRect QLineEdit::cursorRect() const
1785{
1786 Q_D(const QLineEdit);
1787 return d->cursorRect();
1788}
1789
1790/*! \reimp
1791 */
1792void QLineEdit::inputMethodEvent(QInputMethodEvent *e)
1793{
1794 Q_D(QLineEdit);
1795
1796 if (echoMode() == PasswordEchoOnEdit && !d->control->passwordEchoEditing()) {
1797 // Clear the edit and reset to normal echo mode while entering input
1798 // method data; the echo mode switches back when the edit loses focus.
1799 // ### changes a public property, resets current content.
1800 d->updatePasswordEchoEditing(true);
1801 clear();
1802 }
1803
1804#ifdef QT_KEYPAD_NAVIGATION
1805 // Focus in if currently in navigation focus on the widget
1806 // Only focus in on preedits, to allow input methods to
1807 // commit text as they focus out without interfering with focus
1808 if (QApplicationPrivate::keypadNavigationEnabled()
1809 && hasFocus() && !hasEditFocus()
1810 && !e->preeditString().isEmpty())
1811 setEditFocus(true);
1812#endif
1813
1814 d->control->processInputMethodEvent(e);
1815
1816#if QT_CONFIG(completer)
1817 if (!e->commitString().isEmpty())
1818 d->control->complete(Qt::Key_unknown);
1819#endif
1820}
1821
1822/*!\reimp
1823*/
1824QVariant QLineEdit::inputMethodQuery(Qt::InputMethodQuery property) const
1825{
1826#ifdef Q_OS_ANDROID
1827 // QTBUG-61652
1828 if (property == Qt::ImEnterKeyType) {
1829 QWidget *next = nextInFocusChain();
1830 while (next && next != this && next->focusPolicy() == Qt::NoFocus)
1831 next = next->nextInFocusChain();
1832 if (next) {
1833 const auto nextYPos = next->mapToGlobal(QPoint(0, 0)).y();
1834 const auto currentYPos = mapToGlobal(QPoint(0, 0)).y();
1835 if (currentYPos < nextYPos)
1836 // Set EnterKey to KeyNext type only if the next widget
1837 // in the focus chain is below current QLineEdit
1838 return Qt::EnterKeyNext;
1839 }
1840 }
1841#endif
1842 return inputMethodQuery(property, QVariant());
1843}
1844
1845/*!\internal
1846*/
1847QVariant QLineEdit::inputMethodQuery(Qt::InputMethodQuery property, QVariant argument) const
1848{
1849 Q_D(const QLineEdit);
1850 switch(property) {
1851 case Qt::ImEnabled:
1852 return isEnabled() && !isReadOnly();
1853 case Qt::ImCursorRectangle:
1854 return d->cursorRect();
1855 case Qt::ImAnchorRectangle:
1856 return d->adjustedControlRect(d->control->anchorRect());
1857 case Qt::ImFont:
1858 return font();
1859 case Qt::ImAbsolutePosition:
1860 case Qt::ImCursorPosition: {
1861 const QPointF pt = argument.toPointF();
1862 if (!pt.isNull())
1863 return QVariant(d->xToPos(pt.x(), QTextLine::CursorBetweenCharacters));
1864 return QVariant(d->control->cursor()); }
1865 case Qt::ImSurroundingText:
1866 return QVariant(d->control->surroundingText());
1867 case Qt::ImCurrentSelection:
1868 return QVariant(selectedText());
1869 case Qt::ImMaximumTextLength:
1870 return QVariant(maxLength());
1871 case Qt::ImAnchorPosition:
1872 if (d->control->selectionStart() == d->control->selectionEnd())
1873 return QVariant(d->control->cursor());
1874 else if (d->control->selectionStart() == d->control->cursor())
1875 return QVariant(d->control->selectionEnd());
1876 else
1877 return QVariant(d->control->selectionStart());
1878 case Qt::ImReadOnly:
1879 return isReadOnly();
1880 case Qt::ImTextBeforeCursor: {
1881 const QPointF pt = argument.toPointF();
1882 if (!pt.isNull())
1883 return d->textBeforeCursor(d->xToPos(pt.x(), QTextLine::CursorBetweenCharacters));
1884 else
1885 return d->textBeforeCursor(d->control->cursor()); }
1886 case Qt::ImTextAfterCursor: {
1887 const QPointF pt = argument.toPointF();
1888 if (!pt.isNull())
1889 return d->textAfterCursor(d->xToPos(pt.x(), QTextLine::CursorBetweenCharacters));
1890 else
1891 return d->textAfterCursor(d->control->cursor()); }
1892 default:
1893 return QWidget::inputMethodQuery(property);
1894 }
1895}
1896
1897/*!\reimp
1898*/
1899
1900void QLineEdit::focusInEvent(QFocusEvent *e)
1901{
1902 Q_D(QLineEdit);
1903 if (e->reason() == Qt::TabFocusReason ||
1904 e->reason() == Qt::BacktabFocusReason ||
1905 e->reason() == Qt::ShortcutFocusReason) {
1906 if (!d->control->inputMask().isEmpty())
1907 d->control->moveCursor(d->control->nextMaskBlank(0));
1908 else if (!d->control->hasSelectedText())
1909 selectAll();
1910 else
1911 updateMicroFocus();
1912 } else if (e->reason() == Qt::MouseFocusReason) {
1913 d->clickCausedFocus = 1;
1914 updateMicroFocus();
1915 }
1916#ifdef QT_KEYPAD_NAVIGATION
1917 if (!QApplicationPrivate::keypadNavigationEnabled() || (hasEditFocus() && ( e->reason() == Qt::PopupFocusReason))) {
1918#endif
1919 d->control->setBlinkingCursorEnabled(true);
1920 QStyleOptionFrame opt;
1921 initStyleOption(&opt);
1922 if ((!hasSelectedText() && d->control->preeditAreaText().isEmpty())
1923 || style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected, &opt, this))
1924 d->setCursorVisible(true);
1925#ifdef QT_KEYPAD_NAVIGATION
1926 d->control->setCancelText(d->control->text());
1927 }
1928#endif
1929#if QT_CONFIG(completer)
1930 if (d->control->completer()) {
1931 d->control->completer()->setWidget(this);
1932 d->connectCompleter();
1933 }
1934#endif
1935 update();
1936}
1937
1938/*!\reimp
1939*/
1940void QLineEdit::focusOutEvent(QFocusEvent *e)
1941{
1942 Q_D(QLineEdit);
1943 if (d->control->passwordEchoEditing()) {
1944 // Reset the echomode back to PasswordEchoOnEdit when the widget loses
1945 // focus.
1946 d->updatePasswordEchoEditing(false);
1947 }
1948
1949 Qt::FocusReason reason = e->reason();
1950 if (reason != Qt::ActiveWindowFocusReason &&
1951 reason != Qt::PopupFocusReason)
1952 deselect();
1953
1954 d->setCursorVisible(false);
1955 d->control->setBlinkingCursorEnabled(false);
1956#ifdef QT_KEYPAD_NAVIGATION
1957 // editingFinished() is already emitted on LeaveEditFocus
1958 if (!QApplicationPrivate::keypadNavigationEnabled())
1959#endif
1960 if (reason != Qt::PopupFocusReason
1961 || !(QApplication::activePopupWidget() && QApplication::activePopupWidget()->parentWidget() == this)) {
1962 if (d->edited && (hasAcceptableInput() || d->control->fixup())) {
1963 emit editingFinished();
1964 d->edited = false;
1965 }
1966 }
1967#ifdef QT_KEYPAD_NAVIGATION
1968 d->control->setCancelText(QString());
1969#endif
1970#if QT_CONFIG(completer)
1971 if (d->control->completer())
1972 d->disconnectCompleter();
1973#endif
1974 QWidget::focusOutEvent(e);
1975}
1976
1977/*!\reimp
1978*/
1979void QLineEdit::paintEvent(QPaintEvent *)
1980{
1981 Q_D(QLineEdit);
1982 QPainter p(this);
1983 QPalette pal = palette();
1984
1985 QStyleOptionFrame panel;
1986 initStyleOption(&panel);
1987 style()->drawPrimitive(QStyle::PE_PanelLineEdit, &panel, &p, this);
1988 QRect r = style()->subElementRect(QStyle::SE_LineEditContents, &panel, this);
1989 r = r.marginsRemoved(d->effectiveTextMargins());
1990 p.setClipRect(r);
1991
1992 QFontMetrics fm = fontMetrics();
1993 int fmHeight = 0;
1994 if (d->shouldShowPlaceholderText())
1995 fmHeight = fm.boundingRect(d->placeholderText).height();
1996 else
1997 fmHeight = fm.boundingRect(d->control->text() + d->control->preeditAreaText()).height();
1998 fmHeight = qMax(fmHeight, fm.height());
1999
2000 Qt::Alignment va = QStyle::visualAlignment(d->control->layoutDirection(), QFlag(d->alignment));
2001 switch (va & Qt::AlignVertical_Mask) {
2002 case Qt::AlignBottom:
2003 d->vscroll = r.y() + r.height() - fmHeight - QLineEditPrivate::verticalMargin;
2004 break;
2005 case Qt::AlignTop:
2006 d->vscroll = r.y() + QLineEditPrivate::verticalMargin;
2007 break;
2008 default:
2009 //center
2010 d->vscroll = r.y() + (r.height() - fmHeight + 1) / 2;
2011 break;
2012 }
2013 QRect lineRect(r.x() + QLineEditPrivate::horizontalMargin, d->vscroll,
2014 r.width() - 2 * QLineEditPrivate::horizontalMargin, fmHeight);
2015
2016 if (d->shouldShowPlaceholderText()) {
2017 if (!d->placeholderText.isEmpty()) {
2018 const Qt::LayoutDirection layoutDir = d->placeholderText.isRightToLeft() ? Qt::RightToLeft : Qt::LeftToRight;
2019 const Qt::Alignment alignPhText = QStyle::visualAlignment(layoutDir, QFlag(d->alignment));
2020 const QColor col = pal.placeholderText().color();
2021 QPen oldpen = p.pen();
2022 p.setPen(col);
2023 Qt::LayoutDirection oldLayoutDir = p.layoutDirection();
2024 p.setLayoutDirection(layoutDir);
2025
2026 const QString elidedText = fm.elidedText(d->placeholderText, Qt::ElideRight, lineRect.width());
2027 p.drawText(lineRect, alignPhText, elidedText);
2028 p.setPen(oldpen);
2029 p.setLayoutDirection(oldLayoutDir);
2030 }
2031 }
2032
2033 int cix = qRound(d->control->cursorToX());
2034
2035 // horizontal scrolling. d->hscroll is the left indent from the beginning
2036 // of the text line to the left edge of lineRect. we update this value
2037 // depending on the delta from the last paint event; in effect this means
2038 // the below code handles all scrolling based on the textline (widthUsed),
2039 // the line edit rect (lineRect) and the cursor position (cix).
2040 int widthUsed = qRound(d->control->naturalTextWidth()) + 1;
2041 if (widthUsed <= lineRect.width()) {
2042 // text fits in lineRect; use hscroll for alignment
2043 switch (va & ~(Qt::AlignAbsolute|Qt::AlignVertical_Mask)) {
2044 case Qt::AlignRight:
2045 d->hscroll = widthUsed - lineRect.width() + 1;
2046 break;
2047 case Qt::AlignHCenter:
2048 d->hscroll = (widthUsed - lineRect.width()) / 2;
2049 break;
2050 default:
2051 // Left
2052 d->hscroll = 0;
2053 break;
2054 }
2055 } else if (cix - d->hscroll >= lineRect.width()) {
2056 // text doesn't fit, cursor is to the right of lineRect (scroll right)
2057 d->hscroll = cix - lineRect.width() + 1;
2058 } else if (cix - d->hscroll < 0 && d->hscroll < widthUsed) {
2059 // text doesn't fit, cursor is to the left of lineRect (scroll left)
2060 d->hscroll = cix;
2061 } else if (widthUsed - d->hscroll < lineRect.width()) {
2062 // text doesn't fit, text document is to the left of lineRect; align
2063 // right
2064 d->hscroll = widthUsed - lineRect.width() + 1;
2065 } else {
2066 //in case the text is bigger than the lineedit, the hscroll can never be negative
2067 d->hscroll = qMax(0, d->hscroll);
2068 }
2069
2070 // the y offset is there to keep the baseline constant in case we have script changes in the text.
2071 // Needs to be kept in sync with QLineEditPrivate::adjustedControlRect
2072 QPoint topLeft = lineRect.topLeft() - QPoint(d->hscroll, d->control->ascent() - fm.ascent());
2073
2074 // draw text, selections and cursors
2075#if QT_CONFIG(style_stylesheet)
2076 if (QStyleSheetStyle* cssStyle = qt_styleSheet(style())) {
2077 cssStyle->styleSheetPalette(this, &panel, &pal);
2078 }
2079#endif
2080 p.setPen(pal.text().color());
2081
2082 int flags = QWidgetLineControl::DrawText;
2083
2084#ifdef QT_KEYPAD_NAVIGATION
2085 if (!QApplicationPrivate::keypadNavigationEnabled() || hasEditFocus())
2086#endif
2087 if (d->control->hasSelectedText() || (d->cursorVisible && !d->control->inputMask().isEmpty() && !d->control->isReadOnly())){
2088 flags |= QWidgetLineControl::DrawSelections;
2089 // Palette only used for selections/mask and may not be in sync
2090 if (d->control->palette() != pal
2091 || d->control->palette().currentColorGroup() != pal.currentColorGroup())
2092 d->control->setPalette(pal);
2093 }
2094
2095 // Asian users see an IM selection text as cursor on candidate
2096 // selection phase of input method, so the ordinary cursor should be
2097 // invisible if we have a preedit string. another condition is when inputmask
2098 // isn't empty,we don't need draw cursor,because cursor and character overlapping
2099 // area is white.
2100 if (d->cursorVisible && !d->control->isReadOnly() && d->control->inputMask().isEmpty())
2101 flags |= QWidgetLineControl::DrawCursor;
2102
2103 d->control->setCursorWidth(style()->pixelMetric(QStyle::PM_TextCursorWidth, &panel, this));
2104 d->control->draw(&p, topLeft, r, flags);
2105
2106}
2107
2108
2109#if QT_CONFIG(draganddrop)
2110/*!\reimp
2111*/
2112void QLineEdit::dragMoveEvent(QDragMoveEvent *e)
2113{
2114 Q_D(QLineEdit);
2115 if (!d->control->isReadOnly() && e->mimeData()->hasFormat("text/plain"_L1)) {
2116 e->acceptProposedAction();
2117 d->control->moveCursor(d->xToPos(e->position().toPoint().x()), false);
2118 d->cursorVisible = true;
2119 update();
2120 }
2121}
2122
2123/*!\reimp */
2124void QLineEdit::dragEnterEvent(QDragEnterEvent * e)
2125{
2126 QLineEdit::dragMoveEvent(e);
2127}
2128
2129/*!\reimp */
2130void QLineEdit::dragLeaveEvent(QDragLeaveEvent *)
2131{
2132 Q_D(QLineEdit);
2133 if (d->cursorVisible) {
2134 d->cursorVisible = false;
2135 update();
2136 }
2137}
2138
2139/*!\reimp */
2140void QLineEdit::dropEvent(QDropEvent* e)
2141{
2142 Q_D(QLineEdit);
2143 QString str = e->mimeData()->text();
2144
2145 if (!str.isNull() && !d->control->isReadOnly()) {
2146 if (e->source() == this && e->dropAction() == Qt::CopyAction)
2147 deselect();
2148 int cursorPos = d->xToPos(e->position().toPoint().x());
2149 int selStart = cursorPos;
2150 int oldSelStart = d->control->selectionStart();
2151 int oldSelEnd = d->control->selectionEnd();
2152 d->control->moveCursor(cursorPos, false);
2153 d->cursorVisible = false;
2154 e->acceptProposedAction();
2155 insert(str);
2156 if (e->source() == this) {
2157 if (e->dropAction() == Qt::MoveAction) {
2158 if (selStart > oldSelStart && selStart <= oldSelEnd)
2159 setSelection(oldSelStart, str.size());
2160 else if (selStart > oldSelEnd)
2161 setSelection(selStart - str.size(), str.size());
2162 else
2163 setSelection(selStart, str.size());
2164 } else {
2165 setSelection(selStart, str.size());
2166 }
2167 }
2168 } else {
2169 e->ignore();
2170 update();
2171 }
2172}
2173
2174#endif // QT_CONFIG(draganddrop)
2175
2176#ifndef QT_NO_CONTEXTMENU
2177/*!
2178 Shows the standard context menu created with
2179 createStandardContextMenu().
2180
2181 If you do not want the line edit to have a context menu, you can set
2182 its \l contextMenuPolicy to Qt::NoContextMenu. To customize the context
2183 menu, reimplement this function. To extend the standard context menu,
2184 reimplement this function, call createStandardContextMenu(), and extend the
2185 menu returned.
2186
2187 \snippet code/src_gui_widgets_qlineedit.cpp 0
2188
2189 The \a event parameter is used to obtain the position where
2190 the mouse cursor was when the event was generated.
2191
2192 \sa setContextMenuPolicy()
2193*/
2194void QLineEdit::contextMenuEvent(QContextMenuEvent *event)
2195{
2196 if (QMenu *menu = createStandardContextMenu()) {
2197 menu->setAttribute(Qt::WA_DeleteOnClose);
2198 menu->popup(event->globalPos());
2199 }
2200}
2201
2202/*! Creates the standard context menu, which is shown
2203 when the user clicks on the line edit with the right mouse
2204 button. It is called from the default contextMenuEvent() handler.
2205 The popup menu's ownership is transferred to the caller.
2206*/
2207
2208QMenu *QLineEdit::createStandardContextMenu()
2209{
2210 Q_D(QLineEdit);
2211 QMenu *popup = new QMenu(this);
2212 popup->setObjectName("qt_edit_menu"_L1);
2213 QAction *action = nullptr;
2214
2215 if (!isReadOnly()) {
2216 action = popup->addAction(QLineEdit::tr("&Undo") + ACCEL_KEY(QKeySequence::Undo));
2217 action->setEnabled(d->control->isUndoAvailable());
2218 action->setObjectName(QStringLiteral("edit-undo"));
2219 setActionIcon(action, QStringLiteral("edit-undo"));
2220 connect(action, &QAction::triggered, this, &QLineEdit::undo);
2221
2222 action = popup->addAction(QLineEdit::tr("&Redo") + ACCEL_KEY(QKeySequence::Redo));
2223 action->setEnabled(d->control->isRedoAvailable());
2224 action->setObjectName(QStringLiteral("edit-redo"));
2225 setActionIcon(action, QStringLiteral("edit-redo"));
2226 connect(action, &QAction::triggered, this, &QLineEdit::redo);
2227
2228 popup->addSeparator();
2229 }
2230
2231#ifndef QT_NO_CLIPBOARD
2232 if (!isReadOnly()) {
2233 action = popup->addAction(QLineEdit::tr("Cu&t") + ACCEL_KEY(QKeySequence::Cut));
2234 action->setEnabled(!d->control->isReadOnly() && d->control->hasSelectedText()
2235 && d->control->echoMode() == QLineEdit::Normal);
2236 action->setObjectName(QStringLiteral("edit-cut"));
2237 setActionIcon(action, QStringLiteral("edit-cut"));
2238 connect(action, &QAction::triggered, this, &QLineEdit::cut);
2239 }
2240
2241 action = popup->addAction(QLineEdit::tr("&Copy") + ACCEL_KEY(QKeySequence::Copy));
2242 action->setEnabled(d->control->hasSelectedText()
2243 && d->control->echoMode() == QLineEdit::Normal);
2244 action->setObjectName(QStringLiteral("edit-copy"));
2245 setActionIcon(action, QStringLiteral("edit-copy"));
2246 connect(action, &QAction::triggered, this, &QLineEdit::copy);
2247
2248 if (!isReadOnly()) {
2249 action = popup->addAction(QLineEdit::tr("&Paste") + ACCEL_KEY(QKeySequence::Paste));
2250 action->setEnabled(!d->control->isReadOnly() && !QGuiApplication::clipboard()->text().isEmpty());
2251 action->setObjectName(QStringLiteral("edit-paste"));
2252 setActionIcon(action, QStringLiteral("edit-paste"));
2253 connect(action, &QAction::triggered, this, &QLineEdit::paste);
2254 }
2255#endif
2256
2257 if (!isReadOnly()) {
2258 action = popup->addAction(QLineEdit::tr("Delete"));
2259 action->setEnabled(!d->control->isReadOnly() && !d->control->text().isEmpty() && d->control->hasSelectedText());
2260 action->setObjectName(QStringLiteral("edit-delete"));
2261 setActionIcon(action, QStringLiteral("edit-delete"));
2262 connect(action, &QAction::triggered,
2263 d->control, &QWidgetLineControl::_q_deleteSelected);
2264 }
2265
2266 if (!popup->isEmpty())
2267 popup->addSeparator();
2268
2269 action = popup->addAction(QLineEdit::tr("Select All") + ACCEL_KEY(QKeySequence::SelectAll));
2270 action->setEnabled(!d->control->text().isEmpty() && !d->control->allSelected());
2271 action->setObjectName(QStringLiteral("select-all"));
2272 setActionIcon(action, QStringLiteral("edit-select-all"));
2273 d->selectAllAction = action;
2274 connect(action, &QAction::triggered, this, &QLineEdit::selectAll);
2275
2276 if (!d->control->isReadOnly() && QGuiApplication::styleHints()->useRtlExtensions()) {
2277 popup->addSeparator();
2278 QUnicodeControlCharacterMenu *ctrlCharacterMenu = new QUnicodeControlCharacterMenu(this, popup);
2279 popup->addMenu(ctrlCharacterMenu);
2280 }
2281 return popup;
2282}
2283#endif // QT_NO_CONTEXTMENU
2284
2285/*! \reimp */
2286void QLineEdit::changeEvent(QEvent *ev)
2287{
2288 Q_D(QLineEdit);
2289 switch(ev->type())
2290 {
2291 case QEvent::ActivationChange:
2292 if (!palette().isEqual(QPalette::Active, QPalette::Inactive))
2293 update();
2294 break;
2295 case QEvent::FontChange:
2296 d->control->setFont(font());
2297 break;
2298 case QEvent::StyleChange:
2299 {
2300 QStyleOptionFrame opt;
2301 initStyleOption(&opt);
2302 d->control->setPasswordCharacter(char16_t(style()->styleHint(QStyle::SH_LineEdit_PasswordCharacter, &opt, this)));
2303 d->control->setPasswordMaskDelay(style()->styleHint(QStyle::SH_LineEdit_PasswordMaskDelay, &opt, this));
2304 }
2305 update();
2306 break;
2307 case QEvent::LayoutDirectionChange:
2308#if QT_CONFIG(toolbutton)
2309 for (const auto &e : d->trailingSideWidgets) { // Refresh icon to show arrow in right direction.
2310 if (e.flags & QLineEditPrivate::SideWidgetClearButton)
2311 static_cast<QLineEditIconButton *>(e.widget)->setIcon(d->clearButtonIcon());
2312 }
2313#endif
2314 d->positionSideWidgets();
2315 break;
2316 default:
2317 break;
2318 }
2319 QWidget::changeEvent(ev);
2320}
2321
2322QT_END_NAMESPACE
2323
2324#include "moc_qlineedit.cpp"
static const char clearButtonActionNameC[]
#define ACCEL_KEY(k)
Definition qlineedit.cpp:56