Make QLineEdit query QCompleter again
-
I want to enable autocompletion in a
QLineEdit
where the autocompletion suggesions are the results of a query to a website using the content of theQLineEdit
.I set a
QCompleter
for theQLineEdit
and set the Model for theQCompleter
to an object of my own classStockCompleter
derived fromQAbstracTableModel
. I connectedQLineEdit::textChanged(const QString&)
to a slotStockCompleter::textChanged(const QString&)
in my class derived fromQAbstracTableModel
. This function then queries a website using aQNetworkAccessManager
and, after the results arrive, updates its model (callingbeginResetModel()
andendResetModel()
) so that the autocomplete suggestions should be shown. Thedata(const QModelIndex&, int)
function always return the current text of theQLineEdit
for theEditRole
.However, I see the following behavior: Whenever I press a key in the
QLineEdit
, immediatelyStockCompleter::data(const QModelIndex&, int)
is called. Since that still contains the "old" autocompletion suggestions (before the key was pressed), nothing matches and no autocompletions are shown. Only after that,StockCompleter::textChanged(const QString&)
is called, which calls the website. When the website is loaded, thedownloadFinished(QNetworkReply*)
function is called and the autocompletion suggestions in my class are updated (callingbeginResetModel()
andendResetModel()
). However, theQLineEdit
does not "ask" theQCompleter
again for suggestions unless I press a key again, when the same procedure starts over again (first asking for completions which at that timepoint do not match the content of theQLineEdit
, then updating the autocompletion suggestions).I tried several things to force the
QLineEdit
to "ask" theQCompleter
for suggestions again after updating the suggestions inStockCompleter::downloadFinished(QNetworkReply*)
, includingcompleter()->setModel(this); lineEdit()->setCompleter(nullptr); lineEdit()->setCompleter(completer()); lineEdit()->setText(query());
Nothing helps. In principle, the
QCompleter
works; if myStockCompleter::data(const QModelIndex&, int)
function always returns "ho" forQEditRole
then theQLineEdit
shows suggestions if I enter "ho". But, of course, I want to update these suggestions after the autocompletion suggestions are downloaded from the website in myStockCompleter::downloadFinished(QNetworkReply*)
function.What am i doing wrong?
-
@Stephan-Lorenzen
I don't claim to understand entirely, and I have not even used aQCompleter
, but in 2009(!) https://stackoverflow.com/questions/1927289/how-to-update-qcompleters-model-dynamically saidIt 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.
and the OP claimed to answer his own question with
Oh, I have found the answer:
Use signal
textEdited
instead oftextChanged
.Debuging QT's source code told me the answer.
Does this help any?