diff options
Diffstat (limited to 'examples/tools/customcompleter')
-rw-r--r-- | examples/tools/customcompleter/customcompleter.pro | 12 | ||||
-rw-r--r-- | examples/tools/customcompleter/customcompleter.qrc | 5 | ||||
-rw-r--r-- | examples/tools/customcompleter/main.cpp | 55 | ||||
-rw-r--r-- | examples/tools/customcompleter/mainwindow.cpp | 118 | ||||
-rw-r--r-- | examples/tools/customcompleter/mainwindow.h | 77 | ||||
-rw-r--r-- | examples/tools/customcompleter/resources/wordlist.txt | 1455 | ||||
-rw-r--r-- | examples/tools/customcompleter/textedit.cpp | 174 | ||||
-rw-r--r-- | examples/tools/customcompleter/textedit.h | 79 |
8 files changed, 1975 insertions, 0 deletions
diff --git a/examples/tools/customcompleter/customcompleter.pro b/examples/tools/customcompleter/customcompleter.pro new file mode 100644 index 0000000..ebaa831 --- /dev/null +++ b/examples/tools/customcompleter/customcompleter.pro @@ -0,0 +1,12 @@ +HEADERS = mainwindow.h \ + textedit.h +SOURCES = main.cpp \ + mainwindow.cpp \ + textedit.cpp +RESOURCES = customcompleter.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/tools/customcompleter +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS customcompleter.pro resources +sources.path = $$[QT_INSTALL_EXAMPLES]/tools/customcompleter +INSTALLS += target sources diff --git a/examples/tools/customcompleter/customcompleter.qrc b/examples/tools/customcompleter/customcompleter.qrc new file mode 100644 index 0000000..d7da1bf --- /dev/null +++ b/examples/tools/customcompleter/customcompleter.qrc @@ -0,0 +1,5 @@ +<!DOCTYPE RCC><RCC version="1.0"> +<qresource prefix="/"> + <file>resources/wordlist.txt</file> +</qresource> +</RCC> diff --git a/examples/tools/customcompleter/main.cpp b/examples/tools/customcompleter/main.cpp new file mode 100644 index 0000000..8e64f6c --- /dev/null +++ b/examples/tools/customcompleter/main.cpp @@ -0,0 +1,55 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QApplication> +#include "mainwindow.h" + +//! [0] +int main(int argc, char *argv[]) +{ + Q_INIT_RESOURCE(customcompleter); + + QApplication app(argc, argv); + MainWindow window; + window.show(); + return app.exec(); +} +//! [0] diff --git a/examples/tools/customcompleter/mainwindow.cpp b/examples/tools/customcompleter/mainwindow.cpp new file mode 100644 index 0000000..8d75ddd --- /dev/null +++ b/examples/tools/customcompleter/mainwindow.cpp @@ -0,0 +1,118 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtGui> +#include "mainwindow.h" +#include "textedit.h" + +//! [0] +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent), completer(0) +{ + createMenu(); + + completingTextEdit = new TextEdit; + completer = new QCompleter(this); + completer->setModel(modelFromFile(":/resources/wordlist.txt")); + completer->setModelSorting(QCompleter::CaseInsensitivelySortedModel); + completer->setCaseSensitivity(Qt::CaseInsensitive); + completer->setWrapAround(false); + completingTextEdit->setCompleter(completer); + + setCentralWidget(completingTextEdit); + resize(500, 300); + setWindowTitle(tr("Completer")); +} +//! [0] + +//! [1] +void MainWindow::createMenu() +{ + QAction *exitAction = new QAction(tr("Exit"), this); + QAction *aboutAct = new QAction(tr("About"), this); + QAction *aboutQtAct = new QAction(tr("About Qt"), this); + + connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); + connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); + connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt())); + + QMenu* fileMenu = menuBar()->addMenu(tr("File")); + fileMenu->addAction(exitAction); + + QMenu* helpMenu = menuBar()->addMenu(tr("About")); + helpMenu->addAction(aboutAct); + helpMenu->addAction(aboutQtAct); +} +//! [1] + +//! [2] +QAbstractItemModel *MainWindow::modelFromFile(const QString& fileName) +{ + QFile file(fileName); + if (!file.open(QFile::ReadOnly)) + return new QStringListModel(completer); + +#ifndef QT_NO_CURSOR + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); +#endif + QStringList words; + + while (!file.atEnd()) { + QByteArray line = file.readLine(); + if (!line.isEmpty()) + words << line.trimmed(); + } + +#ifndef QT_NO_CURSOR + QApplication::restoreOverrideCursor(); +#endif + return new QStringListModel(words, completer); +} +//! [2] + +//! [3] +void MainWindow::about() +{ + QMessageBox::about(this, tr("About"), tr("This example demonstrates the " + "different features of the QCompleter class.")); +} +//! [3] + diff --git a/examples/tools/customcompleter/mainwindow.h b/examples/tools/customcompleter/mainwindow.h new file mode 100644 index 0000000..77089c2 --- /dev/null +++ b/examples/tools/customcompleter/mainwindow.h @@ -0,0 +1,77 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include <QMainWindow> + +QT_BEGIN_NAMESPACE +class QAbstractItemModel; +class QComboBox; +class QCompleter; +class QLabel; +class QLineEdit; +class QProgressBar; +QT_END_NAMESPACE +class TextEdit; + +//! [0] +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: + MainWindow(QWidget *parent = 0); + +private slots: + void about(); + +private: + void createMenu(); + QAbstractItemModel *modelFromFile(const QString& fileName); + + QCompleter *completer; + TextEdit *completingTextEdit; +}; +//! [0] + +#endif // MAINWINDOW_H diff --git a/examples/tools/customcompleter/resources/wordlist.txt b/examples/tools/customcompleter/resources/wordlist.txt new file mode 100644 index 0000000..a5de826 --- /dev/null +++ b/examples/tools/customcompleter/resources/wordlist.txt @@ -0,0 +1,1455 @@ +A4 +able +about +above +absence +absolutely +abstract +access +according +accumulated +achieve +achieving +activity +acts +actual +actually +add +added +adding +addition +additionally +additions +addresses +adjust +adjustments +advanced +advice +after +afterwards +again +agenda +aim +algorithm +all +allocated +allow +allowed +allowing +allows +along +alpha +already +also +alternative +alternatively +although +American +an +and +announced +annoy +another +answer +answers +any +anything +anyway +apart +API +appear +appears +appendices +appendix +appends +application +applications +apply +approach +approaches +appropriate +Arabic +arbitrary +are +areas +ARGB +argument +arguments +around +arrangements +arrive +arrived +Arthur +article +articles +as +asked +aspects +assume +at +attachment +attempt +attempting +attend +attendees +attributes +authors +availability +available +avoid +away +back +background +backgrounds +bandwidth +bandwidths +Barcelona +base +based +basic +basically +basics +be +because +been +before +behave +behavior +behind +being +below +benefits +Berkeley +between +bit +bits +bitwise +black +blended +blending +blends +block +blue +BMP +body +bold +booking +bool +Boston +both +bottom +box +boxes +braces +break +breaks +broad +browsers +buffer +buffers +build +builds +built +bundled +burdens +busy +but +by +bypass +bypassing +bytes +calendar +call +called +calling +calls +Cambridge +can +canonical +canonicalised +cap +capabilities +capacity +caption +card +care +case +cast +catch +causing +centre +certain +challenges +chance +change +changes +changing +channel +channels +chapter +char +chart +charts +check +checks +Chicago +chosen +chunk +circle +citation +city +claim +class +classes +clause +clauses +clear +clearing +client +clients +close +closed +code +colon +color +colorize +colorizer +colors +colour +column +columns +combine +combined +combines +combining +comes +command +commands +comment +common +communicate +community +compiled +complement +complete +completely +completeness +completes +completion +complex +compliant +component +components +compositing +composition +compression +computation +computer +concepts +conclusion +concurrent +configurable +congested +congestion +connect +connected +connection +connections +cons +consider +consisting +consists +construct +constructed +constructing +constructor +constructs +consume +contact +contain +containing +contains +contents +contents +continue +continued +contributors +control +controlled +controller +controller +controlling +controls +controls +conventions +cook +cooperation +copy +copyright +core +cores +corollary +correct +correctly +corresponding +could +couple +coworkers +CPU +create +creates +creating +crucial +cultures +current +currently +custom +customized +cut +data +database +datasets +datum +day +days +deal +dealing +decide +decouple +decoupled +deeply +def +default +define +defines +definition +definitions +delegate +delete +demo +demonstrate +demonstrations +deployed +describe +describes +design +desktop +desktops +destination +destinations +destructor +details +detect +determine +determines +developer +developers +development +developments +device +devices +diagram +dialogs +dictionary +did +difference +differences +different +differs +digital +direct +direct +directions +directly +directory +discuss +display +displaying +displays +distribute +distribution +disturbing +divide +do +documentation +documents +does +done +down +downLimit +download +downloaded +downloading +draw +drawing +drawn +drop +Duff +during +DVD +dynamic +dynamically +dynamics +each +earlier +easily +editing +editors +education +effect +effectively +effects +either +ellipse +ellipses +elliptical +else +email +embedded +emit +emits +empty +enable +enables +encapsulates +enclose +end +endnote +endnotes +engineer +engineering +English +enjoys +enough +ensure +ensures +entails +enter +entire +entitled +entries +entry +environment +erases +error +errors +especially +established +etc. +Europe +even +evenly +event +events +eventually +every +everyone +example +examples +except +exception +excessive +exclusive +existing +exists +expand +expected +expense +export +exposes +extend +extended +extending +extensible +extension +external +extra +extract +faces +facilities +factory +fade +failure +fairness +falls +false +family +fashion +fast +faster +features +February +feedback +feel +fetch +fetching +few +fields +figure +figures +file +file name +files +filled +filler +final +finally +find +fine +finish +finished +first +flow +fly +focus +followed +following +font +foot +footnote +footnotes +for +form +format +formats +forms +formula +formulas +forum +found +framework +France +from +front +full +fully +function +functionality +functions +future +gain +games +gap +general +generic +Germany +get +gill +give +given +gives +giving +global +go +goes +got +gradient +graph +graphical +graphics +gray +great +greatly +green +grey +group +growing +gui +GUI +hack +had +half +Hamburg +hand +handing +handle +handler +handlers +handles +handling +happens +hardware +harmonica +has +have +having +he +head +header +headers +hear +height +help +helper +here +high +highlight +highly +hints +his +hold +holder +holding +hole +home +horizontal +host +hosting +hours +Houston +how +however +huge +hyphen +ID +idea +ideally +if +Illinois +illustrate +illustrated +illustrates +image +images +impact +implement +implementation +implementations +implemented +implementing +implements +import +important +improvements +in +include +included +includes +including +inclusion +incoming +inconvenient +indent +index +indicate +inexpensively +influence +info +information +ingenious +inherits +initial +initially +inner +input +inspired +install +installs +instance +instead +instructs +integer +integers +integration +intended +intensive +interest +interests +interface +interfaces +interfere +internal +interval +into +intriguing +intro +introduce +introduced +invalid +invented +inverse +invocation +involved +Irish +irregular +is +ISO +ISPs +issue +issues +it +items +iterate +its +itself +job +join +JPEG +jungle +just +Karaoke +keep +keeping +key +kind +king +known +label +labels +landscape +language +large +last +later +latest +lawn +layout +lead +leader +leaders +lean +leaves +leaving +left +lemma +length +less +let +level +levels +libraries +library +lies +like +likely +limit +limiting +limits +line +linear +lines +linewidth +link +linked +linking +Linux +list +lists +little +lives +load +loading +loads +located +location +locations +logo +long +longer +look +looked +looking +looks +lookup +lookups +loop +lout +low +macro +made +magazine +magic +main +major +make +makes +making +manage +managed +managing +mandatory +manipulate +manipulation +manner +many +map +maps +March +margin +mask +masking +Massachusetts +match +mathematical +maximum +may +means +meet +member +members +memory +merged +method +might +milliseconds +minimize +minimum +minor +mix +MNG +mode +model +models +modes +modified +module +moments +monitored +monthly +more +most +mostly +move +much +multitude +Munich +must +name +named +names +necessary +need +needed +needs +network +new +news +newsletter +next +nicely +no +none +normally +Norway +not +note +notes +nothing +notifies +notify +now +null +number +numbered +numbering +numbers +Nydalen +object +objects +obtain +obtaining +odd +of +off +office +offset +offsets +often +old +on +once +one +ones +online +only +onto +opacity +opaque +open +opens +operates +operating +operation +operations +operator +opportunity +opposed +optimize +option +optionally +options +or +OR +order +ordinary +original +originally +Oslo +other +otherwise +our +out +outer +outgoing +output +outside +over +overcoming +overrides +overview +own +owner +owners +pace +Pacific +package +packages +packets +page +pages +paint +painted +painting +paragraph +paragraphs +parameters +parent +Paris +parse +part +partial +partially +particular +partners +parts +party +passed +passing +patches +path +pattern +patterns +pause +PDF +peek +pending +perform +performed +performs +permission +permutations +personal +pick +pie +pipe +pixel +pixels +place +places +planning +platforms +play +players +playing +please +pleasing +plugin +plugins +plus +PNG +pointer +pop +popular +populates +porter +Porter +portrait +possibility +possible +potential +potentially +power +powers +preceded +presence +present +prevent +prevents +previous +previously +primarily +primary +primitives +printed +printing +prior +probably +problem +process +processes +processing +produce +produced +produces +products +programming +programs +project +projects +proof +proper +properly +properties +property +proposed +proposition +pros +protocols +proud +provide +provided +provides +provision +proxy +public +published +punch +punches +pursuing +put +Qt +Qtopia +quality +quarter +quarterly +queried +queries +query +question +questions +radial +ragged +range +rate +rates +rather +ratio +raw +read +reader +reading +reads +ready +real +realistic +really +received +recent +recognized +recommended +recompile +rectangle +rectangular +red +redistribute +reducing +reference +references +reflect +regardless +regional +register +registered +registration +reimplement +reimplementation +reimplemented +release +released +releases +reliable +rely +remains +remember +removed +removes +repeatedly +replace +report +represent +represented +represents +reproduced +requested +require +required +requires +resetting +resides +resolve +respective +respectively +response +rest +restart +result +resulting +resume +return +returning +returns +reuse +revealing +rich +riches +right +roadshow +role +Roman +router +routers +rule +run +runner +runners +running +runs +sake +sales +salespeople +same +sample +San Jose +save +saved +saves +say +scalable +scale +scanline +scene +scenes +schedule +school +script +seam +seamless +search +searches +searching +second +seconds +section +sections +security +see +seen +selection +seminar +seminars +sending +separated +separates +series +service +services +set +setting +setup +seven +seventh +several +shade +shadow +shape +shares +shaves +shine +shorter +should +show +shown +shows +side +signal +signals +signature +significantly +similar +similarily +similarly +simple +simplest +simplified +simplifying +simply +simulate +simultaneous +since +single +size +sizes +slightly +slope +slot +slowing +small +smaller +so +socket +sockets +software +solutions +solved +some +soon +sort +sorting +source +sources +south +space +special +specialized +specific +specifically +specification +specifications +specified +specify +speed +spend +split +SQL +standard +standards +start +starts +starve +state +states +static +steady +stealing +step +still +stop +stopwatch +store +stored +stores +straightforward +stream +string +strings +structure +structured +strut +style +styles +styling +subclass +subclassing +subdirectory +subsection +subsections +succeeds +success +successful +successfully +such +suggestion +suggestions +suitable +support +supported +supports +suppose +supposes +sure +switch +switches +symbol +symbols +synonyms +system +systems +table +tables +tags +take +takes +tap +target +targets +TCP +team +technique +technology +template +templates +Texas +text +than +that +the +their +them +then +theorem +there +these +they +thickness +thin +third +this +those +three +throttling +through +tightly +time +timer +times +tiny +tips +title +titles +to +together +too +top +torrent +total +tour +trademarks +traffic +training +transaction +transfer +transferred +transferring +transfers +translucency +translucent +transparency +transparent +travel +traveled +Trolltech +true +try +turn +twice +two +type +typed +typical +typically +unable +under +underlying +understanding +undoes +unique +united +unlike +unpack +unsigned +until +untouched +up +update +updated +updates +upload +uploading +uploads +us +use +used +useful +user +users +uses +using +usual +usually +valid +value +values +variable +variation +variety +various +vector +venturing +verifying +versa +version +versions +vertical +very +via +vice +virtual +visual +void +VP +waiting +Wales +want +wants +was +way +ways +we +web +website +well +were +what +when +whenever +where +whether +which +while +whistle +white +who +whole +why +widget +widgets +width +widths +will +window +windows +wish +with +without +word +words +work +working +works +would +wrap +wrapper +write +writes +writing +writings +written +X +X11 +XOR +year +years +yes +you +your +zero diff --git a/examples/tools/customcompleter/textedit.cpp b/examples/tools/customcompleter/textedit.cpp new file mode 100644 index 0000000..ecafa8f --- /dev/null +++ b/examples/tools/customcompleter/textedit.cpp @@ -0,0 +1,174 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "textedit.h" +#include <QCompleter> +#include <QKeyEvent> +#include <QAbstractItemView> +#include <QtDebug> +#include <QApplication> +#include <QModelIndex> +#include <QAbstractItemModel> +#include <QScrollBar> + +//! [0] +TextEdit::TextEdit(QWidget *parent) +: QTextEdit(parent), c(0) +{ + setPlainText(tr("This TextEdit provides autocompletions for words that have more than" + " 3 characters. You can trigger autocompletion using ") + + QKeySequence("Ctrl+E").toString(QKeySequence::NativeText)); +} +//! [0] + +//! [1] +TextEdit::~TextEdit() +{ +} +//! [1] + +//! [2] +void TextEdit::setCompleter(QCompleter *completer) +{ + if (c) + QObject::disconnect(c, 0, this, 0); + + c = completer; + + if (!c) + return; + + c->setWidget(this); + c->setCompletionMode(QCompleter::PopupCompletion); + c->setCaseSensitivity(Qt::CaseInsensitive); + QObject::connect(c, SIGNAL(activated(const QString&)), + this, SLOT(insertCompletion(const QString&))); +} +//! [2] + +//! [3] +QCompleter *TextEdit::completer() const +{ + return c; +} +//! [3] + +//! [4] +void TextEdit::insertCompletion(const QString& completion) +{ + if (c->widget() != this) + return; + QTextCursor tc = textCursor(); + int extra = completion.length() - c->completionPrefix().length(); + tc.movePosition(QTextCursor::Left); + tc.movePosition(QTextCursor::EndOfWord); + tc.insertText(completion.right(extra)); + setTextCursor(tc); +} +//! [4] + +//! [5] +QString TextEdit::textUnderCursor() const +{ + QTextCursor tc = textCursor(); + tc.select(QTextCursor::WordUnderCursor); + return tc.selectedText(); +} +//! [5] + +//! [6] +void TextEdit::focusInEvent(QFocusEvent *e) +{ + if (c) + c->setWidget(this); + QTextEdit::focusInEvent(e); +} +//! [6] + +//! [7] +void TextEdit::keyPressEvent(QKeyEvent *e) +{ + if (c && c->popup()->isVisible()) { + // The following keys are forwarded by the completer to the widget + switch (e->key()) { + case Qt::Key_Enter: + case Qt::Key_Return: + case Qt::Key_Escape: + case Qt::Key_Tab: + case Qt::Key_Backtab: + e->ignore(); + return; // let the completer do default behavior + default: + break; + } + } + + bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E + if (!c || !isShortcut) // dont process the shortcut when we have a completer + QTextEdit::keyPressEvent(e); +//! [7] + +//! [8] + const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier); + if (!c || (ctrlOrShift && e->text().isEmpty())) + return; + + static QString eow("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-="); // end of word + bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift; + QString completionPrefix = textUnderCursor(); + + if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3 + || eow.contains(e->text().right(1)))) { + c->popup()->hide(); + return; + } + + if (completionPrefix != c->completionPrefix()) { + c->setCompletionPrefix(completionPrefix); + c->popup()->setCurrentIndex(c->completionModel()->index(0, 0)); + } + QRect cr = cursorRect(); + cr.setWidth(c->popup()->sizeHintForColumn(0) + + c->popup()->verticalScrollBar()->sizeHint().width()); + c->complete(cr); // popup it up! +} +//! [8] + diff --git a/examples/tools/customcompleter/textedit.h b/examples/tools/customcompleter/textedit.h new file mode 100644 index 0000000..d727228 --- /dev/null +++ b/examples/tools/customcompleter/textedit.h @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain +** additional rights. These rights are described in the Nokia Qt LGPL +** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this +** package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef TEXTEDIT_H +#define TEXTEDIT_H + +#include <QTextEdit> + +QT_BEGIN_NAMESPACE +class QCompleter; +QT_END_NAMESPACE + +//! [0] +class TextEdit : public QTextEdit +{ + Q_OBJECT + +public: + TextEdit(QWidget *parent = 0); + ~TextEdit(); + + void setCompleter(QCompleter *c); + QCompleter *completer() const; + +protected: + void keyPressEvent(QKeyEvent *e); + void focusInEvent(QFocusEvent *e); + +private slots: + void insertCompletion(const QString &completion); + +private: + QString textUnderCursor() const; + +private: + QCompleter *c; +}; +//! [0] + +#endif // TEXTEDIT_H + |