I'm trying to learn some Qt programming (C++) and for everything UI-related I come from C# with WPF/MVVM. The problem is that I'm having problems switching the reasoning process behind my choices.
What I'm trying to do is to link a list (or vector or some kind of ObservableCollection) of Objects to a list of Buttons so that the UI will display a button for each element in the list.
Let's say that I have a Customer class (which in C# would be my Model) with 2 variables (plus get/ set methods, or "Properties" as they are called in C#): Name and Type. Each button will display the corresponding Name and the click will send the Type to the method that handles the call.
Now, I cannot have access to a machine with VS these days but in C# I would do something like creating a View and a ViewModel (i.e. the Controller). In the VM I would create an ObservableCollection of Customers that raises the RaisePropertyChanged event when it's modified and in the View I would create an ItemsControl binded to the ObservableCollection with as DataTemplate the Button. The button would have its Content property binded to the Name of the Customer and with CommandParameter (i.e. the parameter sended with the click event) the Model itself or the Customer Type, to make different choices based on its value. This way changing the ObservableCollection would modify the number of Buttons showed.
Now my problem is: how to do the same in Qt? The best I came up with is to create a vector of this Customer class and in a for cycle:
for (unsigned int i = 0; i < model_vector.size(); ++i)
{
QPushButton* btn = new QPushButton(this);
btn->setText(model_vector[i].Name);
ui->verticalLayout->addWidget(btn);
connect(btn, SIGNAL (released()),this, SLOT (handleButton(model_vector[i])));
btn->show();
}
I would put this cycle in a method that is called to update the model_vector so I would clear the verticalLayout and re-add all the Buttons that are contained in the vector at the moment.
Anyhow this doesn't seem to me a real Model/View approach (in the sense I read on the Qt docs), but maybe I'm just misunderstanding how Qt works.
Is what I'm doing correct or is there a better way?
Thanks!
Your original approach sounds a lot like what you would do with a QtQuick based UI.
A model would provide the data, a QtQuick
ListView
(or similar) would provide the general view capability and mediate between the model and the actual entry visualizations, called delegates. The delegate in this case would be a button.