Crash when trying to change QCompleter
Solved
General and Desktop
-
Here is the full source code. What I'm trying to do is create a QCompleter where I can update the list as the user types stuff in. Changing an external model does not seem to work, so I tried to change it by creating a new QCompleter each time. However, that results in a crash. If you run the code below and just type in "comp" it will crash.
So, any ideas on:
- What is the proper way to update the completions for a QCompleter?
- Why this is crashing?
#include <QLineEdit> #include <QApplication> #include <QCompleter> int main(int argc, char *argv[]) { QApplication a(argc, argv); QLineEdit edit; edit.connect(&edit,&QLineEdit::textChanged, &edit,[&edit]() { auto list = QStringList() << "completion1" << "completion2" << "completion3"; auto completer = new QCompleter(list,&edit); edit.setCompleter(completer); }); edit.show(); return a.exec(); }
-
Here is the ultimate solution. After getting a
QSqlQueryModel
to work, I compared the code ofQSqlQueryModel
andQStringListModel
and realized that the only difference was a call tobegin/endInsertRows
. And voila, it worked.For completless sake:
#include <QLineEdit> #include <QApplication> #include <QCompleter> #include <QStringListModel> struct MyStringListModel : public QStringListModel { public: using QStringListModel::QStringListModel; void setStringList(QStringList const & list) { QStringListModel::setStringList(list); Q_EMIT beginInsertRows(QModelIndex(),0,list.size()-1); Q_EMIT endInsertRows(); } }; int main(int argc, char *argv[]) { QApplication app(argc, argv); QLineEdit edit; MyStringListModel model; QCompleter completer(&model,&edit); edit.setCompleter(&completer); edit.connect(&edit,&QLineEdit::textChanged, &model,[&model]() { auto lst = model.stringList(); lst << QString("completion-%1").arg(lst.size()); model.setStringList(lst); }); edit.show(); return app.exec(); }