[QT programming] Automatic completion Function

Source: Internet
Author: User

Recently I wrote a software similar to youdao dictionary for word search, which has an automatic complementing function (that is, when you enter a letter, several candidate items will appear ). This auto-completion function is very common and will appear when Baidu searches for keywords. However, these complementing functions match the first word you enter, and sometimes it is not convenient. For example, if I enter "good", if it is a first-character match, it will appear:

If it is a match in a sentence, this is the case:

You can select a mode based on your requirements. Qt comes with the qcompleter class to implement the above Automatic completion function. Readers can easily learn how to use this class in the demo of QT. Next I will talk about constructing a class that is more powerful than qcompleter.. Some people may say, why do they need to write a class on their own if they are ready-made? Because, when I used the qcompleter class, I found that it only has the match mode of the first sentence (maybe I did not read the document carefully and did not know how to change the pattern). Second, when my dictionary is very large, sometimes the drop-down auto-Completion list will not appear, and the specific reasons are unclear. Therefore, I wrote a class to implement the functionality that the qcompleter class does not have. For more information, see the Code directly (the code annotation is more detailed, so I will not explain it carefully, the widget. UI file is not provided, it is an empty Interface): 1. widget. h
#ifndef WIDGET_H#define WIDGET_H#include <QWidget>#include<QMouseEvent>namespace Ui {class Widget;}class Widget : public QWidget{    Q_OBJECT    public:    explicit Widget(QWidget *parent = 0);    ~Widget();    void mousePressEvent(QMouseEvent *event);private:    Ui::Widget *ui;signals:    void movesignal();};#endif // WIDGET_H

2. completelineedit. h
# Ifndef define # define completelineedit_h # include <qlineedit> # include <qstringlist> # include <qfile> # include <qtextcodec> # include <qdebug> class qlistview; Class qstringlistmodel; Class qmodelindex; class completelineedit: Public qlineedit {q_objectpublic: completelineedit (qstringlist words, qwidget * parent = 0); Public slots: void setcompleter (const qstring & text ); // dynamic display Completion list void completetext (const qmodelindex & Index); // click Finish in the list to use this option to automatically complete the input word protected: virtual void keypressevent (qkeyevent * E); Virtual void focusoutevent (qfocusevent * E); Private slots: void replymovesignal (); Private: qstringlist words; // The word qlistview * listview for the complete list; // The completed list qstringlistmodel * model; // The completed list model}; # endif // completelineedit_h

3. widget. cpp
#include "widget.h"#include "ui_widget.h"Widget::Widget(QWidget *parent) :    QWidget(parent),    ui(new Ui::Widget){    ui->setupUi(this);}Widget::~Widget(){    delete ui;}void Widget::mousePressEvent(QMouseEvent *event){    emit movesignal();}

4. completelineedit. cpp
# Include "completelineedit. H "# include <qkeyevent> # include <qlistview> # include <qstringlistmodel> # include <qdebug> completelineedit: completelineedit (qstringlist words, qwidget * parent): qlineedit (parent ), words (words) {listview = new qlistview (this); // used to display the drop-down list model = new qstringlistmodel (this); listview-> setwindowflags (QT: tooltip ); // set the style connect (this, signal (textchanged (const qstring &), th Is, slot (setcompleter (const qstring &); Connect (listview, signal (clicked (const qmodelindex &), this, slot (completetext (const qmodelindex &);} void completelineedit: focusoutevent (qfocusevent * E) {// listview-> hide (); // hide the automatically completed drop-down list} void completelineedit: replymovesignal () {listview-> hide () when the input row is not focused, hide auto-completion drop-down list} void completelineedit: keypressevent (qkeyevent * E) {If (! Listview-> ishidden () {int key = e-> key (); int COUNT = listview-> model ()-> rowcount (); qmodelindex currentindex = listview-> currentindex (); If (QT: key_down = Key) {// If you press the downward arrow key, int ROW = currentindex. row () + 1; if (row> = count) {ROW = 0;} qmodelindex Index = listview-> model ()-> index (row, 0 ); listview-> setcurrentindex (INDEX);} else if (QT: key_up = Key) {// int ROW = currentindex when you press the downward arrow key. row ()-1; if (row <0) {ROW = count-1;} qmodelindex Index = listview-> model ()-> index (row, 0 ); listview-> setcurrentindex (INDEX);} else if (QT: key_escape = Key) {// hide the completed list listview-> hide ();} else if (QT: key_enter = Key | QT: key_return = Key) {// when you press the Enter key, use the items in the Completion list, and hide the complete list if (currentindex. isvalid () {qstring text = listview-> currentindex (). data (). tostring (); settext (text);} List View-> hide ();} else {// other situations, hide the Completion list, and press the event listview-> hide (); qlineedit on the keyboard of qlineedit :: keypressevent (e) ;}} else {qlineedit: keypressevent (e) ;}} void completelineedit: setcompleter (const qstring & text) {If (text. isempty () // {listview-> hide (); return;} If (text. length ()> 1 )&&(! Listview-> ishidden () {return;} // if a word in the complete Completion list contains the input text, add the qstringlist SL in the list of completion items to be displayed; foreach (qstring word, words) {// fill Mode 1 If (word. contains (text) // It is displayed as long as it contains the input content. You can also set case insensitive {SL <word ;}// fill Mode 2 // If (word. indexof (text, 0, QT: caseinsensitive) = 0) // The content must be the same as the first sentence. // SL <word;} model-> setstringlist (SL ); listview-> setmodel (model); If (model-> rowcount () = 0) {return ;} // set the position and size of the list. listview-> setminimumwidth (width (); listview-> setmaximumwidth (width (); qpoint P (0, height ()); int x = maptoglobal (P ). X (); int y = maptoglobal (P ). Y () + 1; listview-> move (x, y); listview-> show ();} void completelineedit: completetext (const qmodelindex & Index) {qstring text = index. data (). tostring (); settext (text); listview-> hide ();}

5. Main. cpp
# Include <qapplication> # include "completelineedit. H "# include" widget. H "int main (INT argc, char * argv []) {qapplication A (argc, argv); qstringlist SL; qfile * infile = new qfile (" input.txt "); // This is your own dictionary if (! Infile-> open (qiodevice: readonly | qiodevice: Text) {qdebug () <"cannot read! ";} While (! Infile-> atend () {qbytearray line = infile-> Readline (); qtextcodec * gbk_codec = qtextcodec: codecforname ("GBK "); qstring gbk_string = gbk_codec-> tounicode (line); If (! Line. isempty () SL <gbk_string.trimmed (); // enter the words in the file into SL} infile-> close (); // close the SL file <"" <"" <"Naive" <"How are you "; widget * w = new widget (); completelineedit * edit = new completelineedit (SL, W); W-> show (); // qobject: connect (W, signal (movesignal (), edit, slot (replymovesignal (); Return a.exe C ();}

Finally, let's put two auto-completion functions used by the word search software:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.