我使用QCompleter和QLineEdit,我想动态更新QCompleter的模型,即模型的内容会根据QLineEdit的文本进行更新。
1) mdic.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);
}我希望当我输入h时,它会给我一个带有h0、h1和h2的自动补全列表,并且我可以使用键盘键来选择项目。但它的行为并不像我预期的那样。
似乎应该在QLineEdit发出textChanged信号之前设置模型。一种方法是重新实现keyPressEvent,但是要获得QLineEdit的文本需要很多条件。
那么,我想知道有没有一种简单的方法来动态更新QCompleter的模型?
发布于 2009-12-19 01:00:09
哦,我找到答案了:
使用信号textEdited而不是textChanged。
调试QT的源代码告诉我答案。
发布于 2014-05-24 00:10:11
您可以使用类似以下内容:
Foo:Foo()
{
...
QLineEdit* le_foodName = new QLineEdit(this);
QCompleter* foodNameAutoComplete = new QCompleter(this);
le_foodName->setCompleter(foodNameAutoComplete);
updateFoodNameAutoCompleteModel();
...
}
// We call this function everytime you need to update completer
void Foo::updateFoodNameAutoCompleteModel()
{
QStringListModel *model;
model = (QStringListModel*)(foodNameAutoComplete->model());
if(model==NULL)
model = new QStringListModel();
// Get Latest Data for your list here
QStringList foodList = dataBaseManager->GetLatestFoodNameList() ;
model->setStringList(foodList);
foodNameAutoComplete->setModel(model);
}发布于 2015-01-29 20:42:32
使用filterMode : Qt::MatchFlags属性。此属性保存过滤的执行方式。如果filterMode设置为Qt::MatchStartsWith,则只显示那些以键入的字符开头的条目。Qt::MatchContains将显示包含键入字符的条目,Qt::MatchEndsWith将显示以键入字符结尾的条目。目前,只有这三种模式在中实现。将filterMode设置为任何其他Qt::MatchFlag都会发出警告,并且不会执行任何操作。默认模式为Qt::MatchStartsWith。
此属性是在Qt 5.2中引入的。
访问功能:
Qt::MatchFlags filterMode() const
void setFilterMode(Qt::MatchFlags filterMode)https://stackoverflow.com/questions/1927289
复制相似问题