如何动态更新QCompleter的模型 [英] How to update QCompleter's model dynamically

查看:431
本文介绍了如何动态更新QCompleter的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将QCompleterQLineEdit一起使用,并且我想动态更新QCompleter的模型.即模型的内容根据QLineEdit的文本进行了更新.

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

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

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);
}

我希望当我输入h时,它应该为我提供一个包含h0h1h2的自动完成列表,并且我可以使用keyborad来选择项目.但这并不像我预期的那样.

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.

似乎应该在QLineEdit发出textChanged信号之前设置模型.一种方法是重新实现keyPressEvent,但要获取QLineEdit的文本涉及很多条件.

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.

所以,我想知道是否有一种简单的方法可以动态更新QCompleter的模型?

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

推荐答案

哦,我找到了答案:

使用信号textEdited代替textChanged.

调试QT的源代码告诉了我答案.

Debuging QT's source code told me the answer.

这篇关于如何动态更新QCompleter的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆