PDA

View Full Version : QCompleter for tree model showing only leaves/children



ce_nort
15th June 2019, 21:41
Hello,
I have a project where I have multiple QComboboxes that I need a QCompleter for. There is a main QCombobox (let's call it parentCombobox) and then there are multiple QComboxes (childComboboxes) whose lists/completions are affected by what is selected in parentCombobox. The data is stored in a tree model using QAbstractItemModl.

To give a simple food-based example of what I am looking for, let's say that the user selected "Breakfast" in rootCombobox(Meal), then I would like the list in childCombobox1(Protein) to show "eggs", "sausage", "bacon", etc and the list in childCombobox2(Carb) to show "toast", "hash browns", etc. If the user selected "Lunch" from the rootCombobox instead, the lists in the childComboboxes would change to proteins and carbs appropriate to that mealtime. The data would be stored in a model that looks like so:
Root
|_Breakfast
| |_Protein
| | |_Eggs
| | |_Sausage
| | |_Bacon
| |_Carbs
| | |_Toast
| | |_Hash Browns
|_Lunch
| |_Protein
| | |_Sliced Turkey
| | |_Sliced Ham
| |_Carbs
| | |_Bread
| | |_Chips
|_Dinner

And so on and so forth. I have reviewed this example: https://doc.qt.io/qt-5/qtwidgets-tools-treemodelcompleter-example.html but my problem is that there are no separators because it's not a file system and user would not be typing in a full path to separate. Is there a way I can achieve what I am looking for by subclassing QCompleter as in the example, or do I need to simply get QStringLists of the leaves in the tree and pass them to individual QCompleters for the comboboxes?

Maybe something that involves using the pathFromIndex function ( https://doc.qt.io/qt-5/qcompleter.html#pathFromIndex ) to create a full path behind the scenes where one doesn't actually exist?

anda_skoa
17th June 2019, 08:08
This sounds like QComboBox::setRootModelIndex() is what you are looking for.

Essentially you set the tree model on all comboboxes and when the "top level" one changes you set the respective branch model index as the "root" for each of the sub comboboxes.

I.e. in your example, when the rootCombobox changes to "Breakfast" you retrieve the model index for "Breakfast->Protein" and set that as the root on childCombobox1

This should result in childCombobox1 only "seeing" the items below that, in your example "Eggs", "Sausage" and "Bacon"

Cheers,
_

ce_nort
17th June 2019, 17:05
Ah, that makes sense, thank you!