views:

92

answers:

1

I use QCompleter with QLineEdit, and I want to update QCompleter's model dynamically. i.e. the model's contents are updated according to QLineEdit's text.

1) mdict.h

#include <QtGui/QWidget>

class QLineEdit;
class QCompleter;
class QModelIndex;

class mdict : public QWidget
{
    Q_OBJECT

public:
    mdict(QWidget *parent = 0);
    ~mdict() {}

private slots:
    void on_textChanged(const QString &text);

private:
    QLineEdit *mLineEdit;
    QCompleter *mCompleter;
};

2) mdict.cpp

#include <cassert>
#include <QtGui>
#include "mdict.h"

mdict::mdict(QWidget *parent) : QWidget(parent), mLineEdit(0), mCompleter(0)
{
    mLineEdit = new QLineEdit(this);
    QPushButton *button = new QPushButton(this);
    button->setText("Lookup");

    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->addWidget(mLineEdit);
    layout->addWidget(button);
    setLayout(layout);

    QStringList stringList;
    stringList << "m0" << "m1" << "m2";
    QStringListModel *model = new QStringListModel(stringList);
    mCompleter = new QCompleter(model, this);
    mLineEdit->setCompleter(mCompleter);

    mLineEdit->installEventFilter(this);

    connect(mLineEdit, SIGNAL(textChanged(const QString&)),
            this, SLOT(on_textChanged(const QString&)));
}

void mdict::on_textChanged(const QString &)
{
    QStringListModel *model = (QStringListModel*)(mCompleter->model());
    QStringList stringList;
    stringList << "h0" << "h1" << "h2";
    model->setStringList(stringList);
}

I expect when I input "h", it should give me a auto-complete list with "h0", "h1", and "h2" and I could use keyborad to select item. But it doesn't behavior as I expected.

It seems that the model should be set before QLineEdit emits "textChanged" signal. One way is to reimplement "keyPressEvent", but it involves many conditions to get QLineEdit's text.

So, I want to know is there an easy way to update QCompleter's model dynamically?

A: 

Oh, I have found the answer:

Use signal "textEdited" instead of "textChanged".

Debuging QT's source code told me the answer.

hu