0

In Qt, the GUI application usually consists of one main window which contains several views/widgets.

It is very common to provide a context menu which contains

  • Add
  • Remove
  • Clear

etc. for a item list view.

If I implements the context menu in the view, in many cases, the view should know the model which makes me think that the design is bad.

If I implements the context menu in the main window, the main window code bloats very quickly when many views exist. This also makes me think that this is bad choice.

Where should I put the code for context menu? in view? or in main window?

slyx
  • 2,063
  • 1
  • 19
  • 28
  • View must know the model. Otherwise it cannot work. That's why `QAbstractItemView::setModel()` function exists. If you need only one menu for many item views, you can add it in the main window. You can refer, for example, to this answer: https://stackoverflow.com/a/22198672/2674506 – vahancho Jun 07 '19 at 08:54
  • 1
    controller must know the model, not the view, the view is dumb and has no logic nor idea about what is the semantic meaning of what it is presenting to the user.... – ΦXocę 웃 Пepeúpa ツ Jun 07 '19 at 08:55
  • 1
    @vahancho When I said 'view knows model', I meant the very specific model derived from QAbstractItemModel and depends on underlying data instead of QAbstractItemModel. It doesn't matter that view knows QAbstractItemModel because it's external dependency which merely changes. – slyx Jun 07 '19 at 09:19
  • @ΦXocę웃Пepeúpaツ Do you mean that I should implement full MVC pattern and put the context menu code in controller? – slyx Jun 07 '19 at 09:20
  • @xylosper, that's why polymorphism is for. – vahancho Jun 07 '19 at 09:26
  • @vahancho Suppose you have a model for type T items. If you implements 'Add' menu in view, how can the view create new T item and add it to model without knowing that the model contains T type items? – slyx Jun 07 '19 at 11:27
  • 2
    @xylosper, view must not create items. It must only show them. Ideally "Add" menu item slot should just call `QAbstractItemModel::insertRow()` function of the corresponding model. The function will create new item. – vahancho Jun 07 '19 at 11:59
  • @vahancho Ah, now I can imagine how it works. Thank you! – slyx Jun 07 '19 at 12:31

0 Answers0