1

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 :(
4

1 回答 1

2

word可以QCompleter使用

QAbstractItemModel *m = completer->model();

如您所见,方法model()返回const指针。

这对检查程序有好处,你可以这样检查:

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;

但是为了您的目的,我建议您声明QStringListModel,并将其连接到您的完成者,然后,根据 Qt 的 MVC 编程原则(http://doc.qt.digia),您必须通过模型执行的所有操作.com/qt/model-view-programming.html)。

你的代码可以是这样的:

// 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");

祝你好运!

于 2012-12-17T10:07:19.140 回答