Time ago I had the task to create a QComboBox and a QLineEdit that open a completer so the user can select between all the suggested options. So far it seems a quite easy task by using the QCompleter that Qt provides.
The interesting part starts when I had to add customized styles for both the QComboBox and the QLineEdit, and make them match with the styles that I also had to add to the QCompleter. In addition I had a language constraint that initially I didn’t take into account but it impacted the performance of the widget. That’s the default filter implemented in QCompleter.
In Spanish we have vowels with diacritics (á, é í, ó, ú) and also a letter (ñ). The default filter in QCompleter differentiates between vowels with and without diacritics as it should. In Spanish the diacritics doesn’t imply a different sound as it happens in other languages. They are used to indicate the stress of the word or to slit a syllable in some special cases. For that reason people usually doesn’t write diacritics in search engines but they expect the search results take them into consideration. That was a “hidden” requirement when the behavior was defined.
Filtering diacritics in QCompleter
After some research I end in this post on StackOverflow (what else?) that explains perfectly what we need. Basically, what we have to do is define two classes that represents the model that we’re going to overload with our behavior and a completer that will overload the default completer behavior.
I’ve merged the instantiations in one place for clarification. So, when we instantiate my custom QCompleter, we pass a list of strings that will go directly to the model. The model will be instantiated and configured inside the custom QCompleter.
Adding styles to QCompleter
Styling the QCompleter is a bit more intuitive that setting the specific behavior we’ve done above. The intuition leads us to modify the styles of QCompleter in our stylesheet. But to make it work we need to use our completer as the controller of a MVC pattern.
We already have the model, since we define it inside the completer. It takes care of providing the data based on a search and our algorithm. Now, what we need, is a way to present the data with the format we want. For that purpose, we need a QListView and that’s why we’re passing it to the completer.
By using a QListView, we’ll be able to style how we want to present our data. In addition, it allows us to play with how we present the data is presented. Since we’re using the list view, we can easily add styles in our CSS file: