Search code examples
qtmodel-view

How to split a complex hierarchical Model into two partial Views?


I'm learning the Model/View paradigm of Qt because it seems very well suited to edit the data structures I have to deal with, such as this one:

Addition  
 |_QuadraticFunction  
 |  |_intercept=0.2  
 |  |_slope=0.0  
 |  |_quadratic=1.2  
 |_Multiplication  
   |_LinearFunction  
   |  |_intercept=0.0  
   |  |_slope=-8.9  
   |_Gaussian  
      |_center=0.6  
      |_sigma=0.4  

My data structure is made up of a combination of functions, each function has its own properties. However, I don't want to display the whole data structure in a single TreeView because it can get too long for complicated structures. Instead, I want to show one view including only the function names, and other view showing only the properties of the function selected in the previous view by the user with a click of the mouse, like this:

(FunctionsView, the first View)

Addition  
 |_QuadraticFunction  
 |_Multiplication  
   |_**LinearFunction**
   |_Gaussian  

(selectedFunctionView, the second View)

intercept 0.0  
slope -8.9  

In this example, the user clicked on LinearFunction in the first View, and the second View automatically showed its properties.
My question is: can I hold all my data structure (function names and function properties) under a single model and then have two Views that display only parts of the model like above? If not, do I have to create one model for each partial View, each model indexing different parts of the data structure? Please help, I'm inexperienced with this.

.Jose


Solution

  • Yes, you can absolutely keep it all in one model with two different views. You'll probably want to look into a QSortFilterProxyModel; you would have one of these for each view. The proxy applies sorting and filtering--and filtering is what you're doing here--to a more complete model. When you select something in the main view, you'll want to issue a signal that's picked up by the other proxy model (or the other view and passed to its proxy), and then refilter based on the newly selected item. It's actually very easy to use overall. The easiest mistake to make is getting confused over which model index to use because you'll have model indexes for the proxies, and model indexes for the complete model, and sometimes you have to convert between the two. The documentation is pretty clear on where that's necessary, but it helps to be extra aware of it.

    Take a look at the documentation and if you have more questions, please ask.