-
Notifications
You must be signed in to change notification settings - Fork 122
/
HintingLineEdit.cpp
94 lines (70 loc) · 2.59 KB
/
HintingLineEdit.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "MantidQtMantidWidgets/HintingLineEdit.h"
#include <boost/algorithm/string.hpp>
#include <QToolTip>
namespace MantidQt
{
namespace MantidWidgets
{
HintingLineEdit::HintingLineEdit(QWidget *parent, const std::map<std::string,std::string> &hints) : QLineEdit(parent), m_hints(hints), m_dontComplete(false)
{
connect(this, SIGNAL(textEdited(const QString&)), this, SLOT(updateHint(const QString&)));
}
HintingLineEdit::~HintingLineEdit()
{
}
void HintingLineEdit::keyPressEvent(QKeyEvent* e)
{
m_dontComplete = (e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete || e->key() == Qt::Key_Space);
QLineEdit::keyPressEvent(e);
}
void HintingLineEdit::updateMatches()
{
m_matches.clear();
for(auto it = m_hints.begin(); it != m_hints.end(); ++it)
{
const std::string& hint = it->first;
if(hint.length() < m_curKey.length())
continue;
const std::string hintPrefix = hint.substr(0, m_curKey.length());
if(m_curKey == hintPrefix)
m_matches[hint] = it->second;
}
}
void HintingLineEdit::updateHint(const QString& text)
{
const size_t curPos = (size_t)cursorPosition();
const std::string line = text.toStdString();
//Get text from start -> cursor
std::string prefix = line.substr(0, curPos);
std::size_t startPos = prefix.find_last_of(",");
if(startPos != std::string::npos)
prefix = prefix.substr(startPos + 1, prefix.size() - (startPos + 1));
boost::trim(prefix);
m_curKey = prefix;
showHint();
}
void HintingLineEdit::insertSuggestion()
{
if(m_curKey.length() < 1 || m_matches.size() < 1 || m_dontComplete)
return;
const std::string key = m_matches.begin()->first;
QString line = text();
const int curPos = cursorPosition();
//Don't perform insertions mid-word
if(curPos + 1 < line.size() && line[curPos+1].isLetterOrNumber())
return;
line = line.left(curPos) + QString::fromStdString(key).mid((int)m_curKey.size()) + line.mid(curPos);
setText(line);
setSelection(curPos, (int)key.size());
}
void HintingLineEdit::showHint()
{
updateMatches();
QString hintList;
for(auto mIt = m_matches.begin(); mIt != m_matches.end(); ++mIt)
hintList += QString::fromStdString(mIt->first) + " : " + QString::fromStdString(mIt->second) + "\n";
QToolTip::showText(mapToGlobal(QPoint(0, 5)), hintList.trimmed());
insertSuggestion();
}
} //namespace MantidWidgets
} //namepsace MantidQt