From cb961007c534b260b779ed513d33843a9dce01f4 Mon Sep 17 00:00:00 2001 From: J-P Nurmi Date: Tue, 27 Nov 2012 14:18:41 +0100 Subject: Examples: move widgets specific "tools" examples to the correct place examples/tools -> examples/widgets/tools Change-Id: I8b9e23c45e07ce5cd9da8f24a9a9f7ae10b2b107 Reviewed-by: hjk --- .../tools/customcompleter/customcompleter.desktop | 11 + .../tools/customcompleter/customcompleter.pro | 16 + .../tools/customcompleter/customcompleter.qrc | 5 + examples/widgets/tools/customcompleter/main.cpp | 54 + .../widgets/tools/customcompleter/mainwindow.cpp | 117 ++ .../widgets/tools/customcompleter/mainwindow.h | 76 + .../tools/customcompleter/resources/wordlist.txt | 1454 ++++++++++++++++++++ .../widgets/tools/customcompleter/textedit.cpp | 173 +++ examples/widgets/tools/customcompleter/textedit.h | 78 ++ 9 files changed, 1984 insertions(+) create mode 100644 examples/widgets/tools/customcompleter/customcompleter.desktop create mode 100644 examples/widgets/tools/customcompleter/customcompleter.pro create mode 100644 examples/widgets/tools/customcompleter/customcompleter.qrc create mode 100644 examples/widgets/tools/customcompleter/main.cpp create mode 100644 examples/widgets/tools/customcompleter/mainwindow.cpp create mode 100644 examples/widgets/tools/customcompleter/mainwindow.h create mode 100644 examples/widgets/tools/customcompleter/resources/wordlist.txt create mode 100644 examples/widgets/tools/customcompleter/textedit.cpp create mode 100644 examples/widgets/tools/customcompleter/textedit.h (limited to 'examples/widgets/tools/customcompleter') diff --git a/examples/widgets/tools/customcompleter/customcompleter.desktop b/examples/widgets/tools/customcompleter/customcompleter.desktop new file mode 100644 index 0000000000..bbc21112ad --- /dev/null +++ b/examples/widgets/tools/customcompleter/customcompleter.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Custom Completer +Exec=/opt/usr/bin/customcompleter +Icon=customcompleter +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/tools/customcompleter/customcompleter.pro b/examples/widgets/tools/customcompleter/customcompleter.pro new file mode 100644 index 0000000000..b61cb510e9 --- /dev/null +++ b/examples/widgets/tools/customcompleter/customcompleter.pro @@ -0,0 +1,16 @@ +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 + +QT += widgets + +simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/tools/customcompleter/customcompleter.qrc b/examples/widgets/tools/customcompleter/customcompleter.qrc new file mode 100644 index 0000000000..d7da1bf9a6 --- /dev/null +++ b/examples/widgets/tools/customcompleter/customcompleter.qrc @@ -0,0 +1,5 @@ + + + resources/wordlist.txt + + diff --git a/examples/widgets/tools/customcompleter/main.cpp b/examples/widgets/tools/customcompleter/main.cpp new file mode 100644 index 0000000000..893c73026d --- /dev/null +++ b/examples/widgets/tools/customcompleter/main.cpp @@ -0,0 +1,54 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#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/widgets/tools/customcompleter/mainwindow.cpp b/examples/widgets/tools/customcompleter/mainwindow.cpp new file mode 100644 index 0000000000..702176eb1e --- /dev/null +++ b/examples/widgets/tools/customcompleter/mainwindow.cpp @@ -0,0 +1,117 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#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/widgets/tools/customcompleter/mainwindow.h b/examples/widgets/tools/customcompleter/mainwindow.h new file mode 100644 index 0000000000..2dae198a49 --- /dev/null +++ b/examples/widgets/tools/customcompleter/mainwindow.h @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include + +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/widgets/tools/customcompleter/resources/wordlist.txt b/examples/widgets/tools/customcompleter/resources/wordlist.txt new file mode 100644 index 0000000000..f8b581a405 --- /dev/null +++ b/examples/widgets/tools/customcompleter/resources/wordlist.txt @@ -0,0 +1,1454 @@ +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 +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/widgets/tools/customcompleter/textedit.cpp b/examples/widgets/tools/customcompleter/textedit.cpp new file mode 100644 index 0000000000..65054e736d --- /dev/null +++ b/examples/widgets/tools/customcompleter/textedit.cpp @@ -0,0 +1,173 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "textedit.h" +#include +#include +#include +#include +#include +#include +#include +#include + +//! [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(QString)), + this, SLOT(insertCompletion(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) // do not 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/widgets/tools/customcompleter/textedit.h b/examples/widgets/tools/customcompleter/textedit.h new file mode 100644 index 0000000000..67d83241e3 --- /dev/null +++ b/examples/widgets/tools/customcompleter/textedit.h @@ -0,0 +1,78 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef TEXTEDIT_H +#define TEXTEDIT_H + +#include + +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 + -- cgit v1.2.3