Search code examples
qtqt4qtexteditqcompleter

Checking then Adding items to QCompleter model


I am currently working on a code editor written in Qt,

I have managed to implement most of the features which I desire, i.e. auto completion and syntax highlighting but there is one problem which I can't figure out.

I have created a model for which the QCompleter uses, which is fine for things like html tags and c++ keywords such as if else etc.

But I would like to add variables to the completer as they are entered by the user.

So I created an event on the QTextEdit which will get the word (I know I need to check to make sure that it is a variable etc but I just want to get it working for now).

void TextEdit::checkWord()
{
    //going to get the previous word and try to do something with it
    QTextCursor tc = textCursor();
    tc.movePosition(QTextCursor::PreviousWord);
    tc.select(QTextCursor::WordUnderCursor);
    QString word = tc.selectedText();
    //check to see it is in the model
}

But now I want to work out how to check to see if that word is already in the QCompleters model and if it isn't how do I add it?

I have tried the following:

QAbstractItemModel *m = completer->model();
//dont know what to do with it now :(

Solution

  • You can check if word is in your QCompleter really by using

    QAbstractItemModel *m = completer->model();
    

    as you can see, method model() returns const pointer.

    That is good for checking procedure, you can check like this:

    bool matched = false;
    QString etalon("second");
    QStringListModel *strModel = qobject_cast<QStringListModel*>(completer.model());
    if (strModel!=NULL)
        foreach (QString str, strModel->stringList()) {
            if (str == etalon)
            {
                matched = true;
                break;
            }
        }
    qDebug()<<matched;
    

    But for your purposes, I recommend you to declare QStringListModel, and connect it to your completer, and then, all of operations you'll must do thru your model, according to Qt's principles of MVC programming (http://doc.qt.digia.com/qt/model-view-programming.html).

    Your code can be like this:

    // declaration
    QCompleter completer;
    QStringListModel completerModel;
    
    // initialization
    completer.setModel(&completerModel);
    QStringList stringListForCompleter;
    stringListForCompleter << "first" << "second" << "third";
    completerModel.setStringList(stringListForCompleter);
    
    // adding new word to your completer list
    completerModel.setStringList(completerModel.stringList() << "New Word");
    

    Good luck!