PDA

View Full Version : Switch between models on click of a button



padma
25th July 2017, 18:57
Hi,

I am currently set ModelA to a view. On clicking a button, I want to toggle between model B and model A in the same view. (The columns remain the same, the number of rows and the data is entirely different).
Both models are of the QStandardItemModel type.

Is there a better and faster way to have the switch other than using view->setmodel every time?


I tried setting a fixed 'mainmodel', which is always set to the view. Then I tried assigning the mainmodel to modelb or modelA and tried to see if these changes reflect instantaneously.
But this did not work, the view did not update on simple assignment.

Can someone please guide me to how this is usually done?

Thanks,
Padma

d_stranz
25th July 2017, 23:52
Is there a better and faster way to have the switch other than using view->setmodel every time?

Not that I know of. If the contents of the two models are completely different, then the view needs to completely update itself no matter how you try to "trick" it.

If the models are different, but their content does not change often, then instead of switching models on a single view, you can try using two views, one for each model, and simply switch the visibility of the views by using something like a QStackedWidget where you add each of the views as a widget in the stack. In this case, changing which model is displayed is as simple as calling QStackedWidget::setCurrentIndex(). Your code to do this could go something like this:



void MyClass::onSwitchViewsClicked()
{
int currentView = mpStackedWidget->currentIndex();
int nextView = (currentView + 1) % 2;
mpStackedWidget->setCurrentIndex( nextView );
}


Repainting after the switch will be instantaneous.