2 Copyright 2013-2015 Mats Sjöberg
4 This file is part of the Pumpa programme.
6 Pumpa is free software: you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Pumpa is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14 License for more details.
16 You should have received a copy of the GNU General Public License
17 along with Pumpa. If not, see <http://www.gnu.org/licenses/>.
20 #include "recipientedit.h"
22 #include <QStringListModel>
25 //------------------------------------------------------------------------------
27 RecipientEdit::RecipientEdit(QWidget
* parent
) :
33 //------------------------------------------------------------------------------
35 void RecipientEdit::setChoices(QStringList choices
) {
40 m_completer
= new QCompleter(this);
41 m_completer
->setWidget(this);
43 m_completer
->setCaseSensitivity(Qt::CaseInsensitive
);
44 QStringListModel
* model
= new QStringListModel(choices
);
45 m_completer
->setModel(model
);
46 //m_completer->setCompletionMode(QCompleter::PopupCompletion);
48 connect(m_completer
, SIGNAL(activated(QString
)),
49 this, SLOT(insertCompletion(QString
)));
52 //------------------------------------------------------------------------------
54 void RecipientEdit::keyPressEvent(QKeyEvent
* event
) {
55 int key
= event
->key();
57 QLineEdit::keyPressEvent(event
);
59 QPair
<int, int> wordPos
= wordPosAtCursor();
60 QString completionPrefix
= text().mid(wordPos
.first
, wordPos
.second
);
61 qDebug() << "completionPrefix" << completionPrefix
;
63 if (completionPrefix
!= m_completer
->completionPrefix()) {
64 m_completer
->setCompletionPrefix(completionPrefix
);
65 m_completer
->popup()->setCurrentIndex(m_completer
->completionModel()->index(0, 0));
68 if (!event
->text().isEmpty() && completionPrefix
.length() > 2) {
69 m_completer
->complete();
73 //------------------------------------------------------------------------------
75 QPair
<int, int> RecipientEdit::wordPosAtCursor() {
76 static QRegExp
whitespace("\\s+");
78 int cur
= cursorPosition();
81 int startPos
= cur
? txt
.lastIndexOf(whitespace
, cur
-1) + 1 : 0;
83 int endPos
= txt
.indexOf(whitespace
, cur
);
87 int len
= endPos
- startPos
;
89 return qMakePair(startPos
, len
);
92 //------------------------------------------------------------------------------
94 void RecipientEdit::insertCompletion(QString completion
) {
95 QPair
<int, int> wordPos
= wordPosAtCursor();
96 setSelection(wordPos
.first
, wordPos
.second
);