1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the examples of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** BSD License Usage
18 ** Alternatively, you may use this file under the terms of the BSD license
19 ** as follows:
20 **
21 ** "Redistribution and use in source and binary forms, with or without
22 ** modification, are permitted provided that the following conditions are
23 ** met:
24 **   * Redistributions of source code must retain the above copyright
25 **     notice, this list of conditions and the following disclaimer.
26 **   * Redistributions in binary form must reproduce the above copyright
27 **     notice, this list of conditions and the following disclaimer in
28 **     the documentation and/or other materials provided with the
29 **     distribution.
30 **   * Neither the name of The Qt Company Ltd nor the names of its
31 **     contributors may be used to endorse or promote products derived
32 **     from this software without specific prior written permission.
33 **
34 **
35 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46 **
47 ** $QT_END_LICENSE$
48 **
49 ****************************************************************************/
50 
51 #include "textedit.h"
52 #include <QCompleter>
53 #include <QKeyEvent>
54 #include <QAbstractItemView>
55 #include <QtDebug>
56 #include <QApplication>
57 #include <QModelIndex>
58 #include <QAbstractItemModel>
59 #include <QScrollBar>
60 
61 //! [0]
TextEdit(QWidget * parent)62 TextEdit::TextEdit(QWidget *parent)
63     : QTextEdit(parent)
64 {
65     setPlainText(tr("This TextEdit provides autocompletions for words that have more than"
66                     " 3 characters. You can trigger autocompletion using ") +
67                     QKeySequence("Ctrl+E").toString(QKeySequence::NativeText));
68 }
69 //! [0]
70 
71 //! [1]
~TextEdit()72 TextEdit::~TextEdit()
73 {
74 }
75 //! [1]
76 
77 //! [2]
setCompleter(QCompleter * completer)78 void TextEdit::setCompleter(QCompleter *completer)
79 {
80     if (c)
81         c->disconnect(this);
82 
83     c = completer;
84 
85     if (!c)
86         return;
87 
88     c->setWidget(this);
89     c->setCompletionMode(QCompleter::PopupCompletion);
90     c->setCaseSensitivity(Qt::CaseInsensitive);
91     QObject::connect(c, QOverload<const QString &>::of(&QCompleter::activated),
92                      this, &TextEdit::insertCompletion);
93 }
94 //! [2]
95 
96 //! [3]
completer() const97 QCompleter *TextEdit::completer() const
98 {
99     return c;
100 }
101 //! [3]
102 
103 //! [4]
insertCompletion(const QString & completion)104 void TextEdit::insertCompletion(const QString &completion)
105 {
106     if (c->widget() != this)
107         return;
108     QTextCursor tc = textCursor();
109     int extra = completion.length() - c->completionPrefix().length();
110     tc.movePosition(QTextCursor::Left);
111     tc.movePosition(QTextCursor::EndOfWord);
112     tc.insertText(completion.right(extra));
113     setTextCursor(tc);
114 }
115 //! [4]
116 
117 //! [5]
textUnderCursor() const118 QString TextEdit::textUnderCursor() const
119 {
120     QTextCursor tc = textCursor();
121     tc.select(QTextCursor::WordUnderCursor);
122     return tc.selectedText();
123 }
124 //! [5]
125 
126 //! [6]
focusInEvent(QFocusEvent * e)127 void TextEdit::focusInEvent(QFocusEvent *e)
128 {
129     if (c)
130         c->setWidget(this);
131     QTextEdit::focusInEvent(e);
132 }
133 //! [6]
134 
135 //! [7]
keyPressEvent(QKeyEvent * e)136 void TextEdit::keyPressEvent(QKeyEvent *e)
137 {
138     if (c && c->popup()->isVisible()) {
139         // The following keys are forwarded by the completer to the widget
140        switch (e->key()) {
141        case Qt::Key_Enter:
142        case Qt::Key_Return:
143        case Qt::Key_Escape:
144        case Qt::Key_Tab:
145        case Qt::Key_Backtab:
146             e->ignore();
147             return; // let the completer do default behavior
148        default:
149            break;
150        }
151     }
152 
153     const bool isShortcut = (e->modifiers().testFlag(Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E
154     if (!c || !isShortcut) // do not process the shortcut when we have a completer
155         QTextEdit::keyPressEvent(e);
156 //! [7]
157 
158 //! [8]
159     const bool ctrlOrShift = e->modifiers().testFlag(Qt::ControlModifier) ||
160                              e->modifiers().testFlag(Qt::ShiftModifier);
161     if (!c || (ctrlOrShift && e->text().isEmpty()))
162         return;
163 
164     static QString eow("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-="); // end of word
165     const bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift;
166     QString completionPrefix = textUnderCursor();
167 
168     if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3
169                       || eow.contains(e->text().right(1)))) {
170         c->popup()->hide();
171         return;
172     }
173 
174     if (completionPrefix != c->completionPrefix()) {
175         c->setCompletionPrefix(completionPrefix);
176         c->popup()->setCurrentIndex(c->completionModel()->index(0, 0));
177     }
178     QRect cr = cursorRect();
179     cr.setWidth(c->popup()->sizeHintForColumn(0)
180                 + c->popup()->verticalScrollBar()->sizeHint().width());
181     c->complete(cr); // popup it up!
182 }
183 //! [8]
184 
185