Model View Controller Design pattern Code Example - c++

I was studying the Model-View-Controller design pattern and i understand the concept behind the pattern theorotically, but I wanted to get a peek at how one would actually put it to practice.
Wikipedia mentions Wt - Web toolkit, CppCMS and some other standard implementations which use the pattern however I have not been familiar with these, and I was just hoping and
will be really grateful If anyone can provide some sample code(hopefully C++) which implements the pattern and explains the theory of the pattern being put to practice.

Here's a quick example I made (didn't try compiling it, let me know if there's errors):
class Button; // Prewritten GUI element
class GraphGUI {
public:
GraphGUI() {
_button = new Button("Click Me");
_model = new GraphData();
_controller = new GraphController(_model, _button);
}
~GraphGUI() {
delete _button;
delete _model;
delete _controller;
}
drawGraph() {
// Use model's data to draw the graph somehow
}
...
private:
Button* _button;
GraphData* _model;
GraphController* _controller;
};
class GraphData {
public:
GraphData() {
_number = 10;
}
void increaseNumber() {
_number += 10;
}
const int getNumber() { return _number; }
private:
int _number;
};
class GraphController {
public:
GraphController(GraphData* model, Button* button) {
__model = model;
__button = button;
__button->setClickHandler(this, &onButtonClicked);
}
void onButtonClicked() {
__model->increaseNumber();
}
private:
// Don't handle memory
GraphData* __model;
Button* __button;
};
Ignoring the implementation of Button, basically this program will use GraphGUI to display a graph that will change when a button is pressed. Let's say it's a bar graph and it will get taller.
Since the model is independent of the view (the button), and the controller handles the communication between the two, this follows the MVC pattern.
When the button is clicked, the controller modifies the model via the onButtonClicked function, which the Button class knows to call when it is clicked.
The beauty of this is since the model and view are completely independent, the implementation of each can drastically change and it won't affect the other, the controller might simply have to make a few changes. If the model in this case calculated some result based off some database data, then clicking the button could cause this to happen, but the button implementation wouldn't have to change. Or, instead of telling the controller when a click occurs, maybe it can tell the controller when the button is moused-over. The same changes are applied to model, regardless of what triggered the changes.

A simple text editor could be designed based on MVC. Think of the string class as the model, where data is stored. We might have a class called SimpleTextView which displays the text in the string attached to it, as it is. A class called KeyboardEventHandler can act as the controller. The controller will notify the view about new keyboard events. The view in turn modifies the model (like appending or removing text). The changes in the model is reflected on all views attached to it. For instance, there might be another view called HtmlView attached to the string object manipulated from within the SimpleTextView. If the user enters valid HTML tags in the SimpleTextView, the HtmlView will display the formatted output - real-time.

There are couple of complete MVC examples, plus discussion, in ch 2 of an introduction to programming in Python 3.x that I wrote (I've not completed ch 3 etc., that project's been on ice for some time -- Python community really like angry swarm of bees when discovered I'd written that Python was perhaps not suitable for very large scale development, so it became difficult to get sensible feedback). It's available in PDF format from Google Docs. I don't know how well it maps to common MVC implementations, I was mostly concerned with getting the general idea across. :-)
Cheers & hth.,
PS: There's a nice table of contents in the PDF file but Google Docs doesn't show it. You'd need to dl and use Foxit or Acrobat or some other PDF viewer. I think there's a separate viewable TOC at Google Docs, though, haven't checked and don't remember whether updated.
PPS: Forgot to mention, the MVC image processing example near the end has nice pic of Lena Söderberg! :)

Code is the best approach to understand and learn Model View Controller:
Here is a simple JS example (from Wiki)
/** Model, View, Controller */
var M = {}, V = {}, C = {};
/** Model stores data */
M.data = "hello world";
/** View controls what to present */
V.render = (M) => { alert(M.data); }
/** Controller bridges View and Model */
C.handleOnload = () => { V.render(M); }
/** Controller on Windows OnLoad event */
window.onload = C.handleOnload;
Here is a detailed post in C/C++
Model-View-Controller Explained in C++

Related

Including a button in a WTableView

I'm working on a Wt-based gui, and struggling with something that feels like it should be very simple:
The gui displays 'events'. In our project we have a model (ActiveEventsModel, based on WStandardItemModel) and a view, (ActiveEventsView, based on WTableView). Currently the view simply shows some text corresponding to various properties of the 'events'. The aim is to add an additional column to the table, contain a button (for example, a WPushButton) which allows the user to "acknowledge" the event shown in that row (in context, this essentially translates to dismissing the event - i.e. each event has a button, and clicking the button will remove that event from the model).
I searched online and found this discussion on the Wt-forum, which contains some guidance on putting a button in (derive from WAbstractItemDelegate and use setItemDelegateForColumn) and a code example for creating a button in an item delegate. After some minor changes for Wt-4.0 compatibility I now have my button in the table.
I've defined a very simple class, EventDelegate, derived from WAbstractItemDelegate:
header:
#include <Ui/WebToolkit.h> //convenience header containing all of the Wt elements we use
class EventDelegate : public Wt::WAbstractItemDelegate
{
public:
EventDelegate();
std::unique_ptr<Wt::WWidget> update(Wt::WWidget *widget, const Wt::WModelIndex &index,
Wt::WFlags<Wt::ViewItemRenderFlag> flags) override;
void acknowledge(Wt::WModelIndex &index);
};
source:
#include <Ui/EventDelegate.h>
EventDelegate::EventDelegate()
: WAbstractItemDelegate()
{
}
std::unique_ptr<Wt::WWidget> EventDelegate::update(Wt::WWidget *widget, const Wt::WModelIndex &index,
Wt::WFlags<Wt::ViewItemRenderFlag> flags)
{
std::unique_ptr<Wt::WWidget> w = std::make_unique<Wt::WPushButton>("acknowledge");
Wt::WPushButton *button = dynamic_cast<Wt::WPushButton*>(w.get());
button->clicked().connect(std::bind(&EventDelegate::acknowledge,this,index));
return w;
}
void EventDelegate::acknowledge(Wt::WModelIndex &index) {
//how do I interact with the model?
}
This seemed promising at first, but I just can't figure out how to actually make the button do anything to the model. I thought maybe I need to override WAbstractItemDelegate::setModelData, but for that I need the model, which the ItemDelegate doesn't seem to know anything about.
I do have the ModelIndex, and the ModelIndex knows which Model it belongs to - but will only give me it as const, which is no use to me because setModelData needs to alter it.
Should I just be giving the Model to the Delegate directly, for example as a constructor parameter? That seems an easy solution but feels very inelegant. Or am I just barking up the wrong tree entirely with how I'm trying to do this? I'm extremely new to Wt (and my colleagues only a little less so - this is a relatively new project and the first in our company that's used Wt) so that's very possible.
(I've not included a whole mcve because I'm pretty sure that what I'm missing here is conceptual. I can add one later if people feel it's really necessary to answer the question)

Should all buttons contain a reference to the controller in MVC code (C++)?

I'm trying to figure out the best (cleanest) way to structure some code in C++ for an application I'm building. I think MVC makes sense as the way to go, but after a fair amount of research I'm not totally clear I'm doing things the right way.
Here's an example to illustrate my question:
Model
I have a class which contains drawing data called Canvas. An example function, used to clear the current contents of the canvas, is ClearCanvas().
Ultimately, I want a button in the interface to be able to call this function and clear the canvas.
Controller
I have a controller class for the canvas: CanvasController
The controller creates and then holds a reference to a canvas object: CurrentCanvas
The controller also creates the view: CanvasView and then sets a reference to itself on the view: CurrentCanvasView->SetControllerRef(this);
View
The view is made up of a series of nested classes that define the UI. For example, the hierarchy leading to the button in question might be something like this:
CanvasView
-VerticalBox
--HorizontalBox
---Button
During the view's constructor, a reference to the controller is passed from the view to all interactive elements, eg. NewButton->SetControllerRef(this->GetControllerRef());
Button Pressed
So now when the button is pressed, it can function like this:
void ClearCanvasButton::OnButtonPressed()
{
Controller->CurrentCanvas->ClearCanvas();
}
So my general question is: (1) does this seem like the right way to be doing things, or badly structured?
Also (2): Should the controller be encapsulating the canvas functions, for example:
void CanvasController::ClearCanvas()
{
CurrentCanvas->ClearCanvas();
}
Such that the function on the button could simply be:
void ClearCanvasButton::OnButtonPressed()
{
Controller->ClearCanvas();
}
I'm just not sure whether it's correct to essentially be passing down a reference to the controller to all elements of the view which ultimately want to change the model, or whether there is a cleaner way.
Apologies if the question has been asked a thousand times in a thousand different ways, I have been searching around trying to understand this.
You don't need a class ClearCanvasButton, if your Button class contains a member like
std::function<void()> onButtonPressed;
or similar, rather than
virtual void onButtonPressed() {};
You then pass a lambda that references the controller
CanvasView::CanvasView()
{
// make the widgets
Button.onButtonPressed = [Controller](){ Controller->ClearCanvas(); };
}

Too deep hierarchy of signals-slots in Qt

I am writing GUI applicaton in Qt. Currently I waste too much time on routine. It seems something wrong with my architecture. Please tell me how can I change my approach to improve code.
What I am doing:
My program can be decomposed as hierarchy of classes (not inheritance but composition). In example:
class D { /* something */ };
class C { /* something */ };
class B { C c1; C c2; D d1; };
class A { D d1; C c1; };
So, actually it is a tree hierarchy where leaf nodes (class C, class D) are "models" in Qt terminology which hold data. At the top of hierarchy MainWindow (class A) is placed, which holds first level of "views" (class D, i.e. subwidget) and leaf node with data (class C, i.e. text field).
To pass information down from main window to data I use function calls from mainwindow (pushbuttons) to leaf nodes. After that data changes and tells parents about it with signal slot mechanism. Parents continue to pass message up with signaling.
I am really bored by establishing all these communication. Now I have up to 5 levels, however it is not that much in usual code when using composition. Please tell me how can I change my approach. Due to complexity of these connections, development of the code extremely slow, almost stopped.
It is hard to give a concrete example, because there are a lot of code, but the idea of problem which is very difficult to solve is following:
There are two QTreeView, which differently shows data from own model inherited from QAbstractItemModel (tree inside model is not that tree in previous discussion, this tree is only single level of hierarchy). I want to select objects in one QTreeView and change by that selection in second QTreeView. There are total 2 QTreeView, 2 different QAbstractItemModel instances, 2 trees of own objects (for each QAbstractItemModel), and single data.
Sounds like you might have become a victim of going through too many examples. Examples tend to cram functionality where it doesn't belong, creating the possibility to develop bad programming habits.
In actual production things need to be more compartmentalized. The main window should not be the container of the "application logic", all it needs to concern itself with is holding together the main widgets.
But that doesn't seem to be your case, judging by the necessity to delegate things "from mainwindow (pushbuttons) to leaf nodes" as you put it.
On a grander scale, it is not advisable to mix application logic with UI at all, much less cram it all in the main window. The application logic should be its own layer, designed so that it can work without any GUI whatsoever, and then the GUI is another layer that simply hooks up to the logic core.
The logic core should not be monolith either, it should be made of individual components focusing on their particular task.
Your use case doesn't really require any crazy amount of connections, just some basic handlers for the UI elements, which should target the logic core API rather than GUI elements as you appear to be doing now.
Your clarification unfortunately makes absolutely no sense to me, it is still completely unclear what you exactly you want to do.
Let's assume your situation is something like this:
Tree 1 shows a folder structure.
Tree 2 shows the file content of the folder, selected in tree 1.
Data is an editor for the file, assuming a text file, selected in tree 2.
So, in pseudocode, presuming that app is your application core logic object:
Clicking an item in tree 1 says app.setFolder(tree1.selectedItem())
Clicking an item in tree 2 says app.setFile(tree2.selectedItem())
Clicking the editor "save" button says app.save(editorUI.dataField.text())
logic layer gui layer
app mainWindow
folder <-----------select----------- tree1
file <-----------select----------- tree2
save(newData) { editor
if (file) file.rewrite(newData) textField
} saveBtn: app.save(textField.text())
Since there is only a single data source, you could do the following:
Create a general model for that data source. The model should represent the data source generally, without consideration of what the views need.
Create two proxy viewmodels that adapt the general model to the needs of the views.
Couple the selection models of the views that display the viewmodels.
Given the selection models on top of the two proxy models that map to the same source, we can propagate the selection change between them. We leverage the selection mapping provided by the proxy. The QAbstractProxyModel has a functional implementation of mapSelectionxxxx.
void applySel(const QItemSelectionModel *src, const QItemSelection &sel,
const QItemSelection &desel, const QItemSelectionModel *dst) {
// Disallow reentrancy on the selection models
static QHash<QObject*> busySelectionModels;
if (busySelectionModels.contains(src) || busySelectionModels.contains(dst))
return;
busySelectionModels.insert(src);
busySelectionModels.insert(dst);
// The models must be proxies
auto *srcModel = qobject_cast<QAbstractProxyItemModel*>(src->model());
auto *dstModel = qobject_cast<QAbstractProxyItemModel*>(dst->model());
Q_ASSERT(srcModel && dstModel);
// The proxies must refer to the same source model
auto *srcSourceModel = srcModel->sourceModel();
auto *dstSourceModel = dstModel->sourceModel();
Q_ASSERT(srcSourceModel && (srcSourceModel == dstSourceModel));
// Convey the selection
auto const srcSel = srcModel->mapSelectionToSource(sel);
auto const srcDesel = srcModel->mapSelectionToSource(desel);
auto const dstSel = dstModel->mapSelectionFromSource(srcSel);
auto const dstDesel = dstModel->mapSelectionFromSource(srcDesel);
// we would re-enter in the select calls
dst->select(dstSel, QItemSelectionModel::Select);
dst->select(dstDesel, QItemSelectionModel::Deselect);
// Allow re-entrancy
busySelectionModels.remove(src);
busySelectionModels.remove(dst);
}
The above could be easily adapted for a list of destination item selection models, in case you had more than two views.
We can use this translation to couple the selection models of the views:
void coupleSelections(QAbstractItemView *view1, QAbstractItemView *view2) {
auto *sel1 = view1->selectionModel();
auto *sel2 = view2->selectionModel();
Q_ASSERT(sel1 && sel2);
connect(sel1, &QItemSelectionModel::selectionChanged,
[=](const QItemSelection &sel, const QItemSelection &desel){
applySel(sel1, sel, desel, sel2);
});
connect(sel2, &QItemSelectionModel::selectionChanged,
[=](const QItemSelection &sel, const QItemSelection &desel){
applySel(sel2, sel, desel, sel1);
});
}
The above is untested and written from memory, but hopefully will work without much ado.

Good design practice concerning MVC view interface

I don't often have to create GUI's but today I do so I was hoping for some design input.
Basically I have a backend which I intend to add a GUI too using the MVC pattern. The issue is I feel whatever class encapsulates the main GUI window is going to have A LOT of state (all of the sub elements); and on top of that it's going to have a lot of setters, and possibly getter, clear, colour, size, position and refresh functions too.
One option is to march ahead with this idea and have a very large public interface which deals with the types the GUI uses (std::string, std::vector<std::string>...) the more control I want over the UI the more public member function I am going to need.
The other option would be to pass the program state to the GUI and have it decide how it display it, I fear doing this would mean it would give me less fine detail control and would break down the separation of concerns and would mean any changes to the representation of the program state would require changes in the GUI too.
Any input on the matter would be of great help.
If it makes any difference this is a C++ gui using an ncurses abstraction.
It sounds like to me you've thought alot about the M and the V, but not much about the C. The pattern should really be called MCV because the whole idea is that the controller IS the bridge between your model (data) and view (GUI). It sounds like you need a controller with most of the functionality you've mentioned.
Simply put though, your model obviously should know nothing about display and your display (view) should not know how to access the model. You need a controller that reads the data (model) and gives instructions to the display (view). If you have user interaction within the view, the controller can interpret that and modify the model as necessary.
The idea is that you never have to change all 3, but if you change the model or the view, you almost always have to update the controller.
Hope that helps...
There is at least one alternative to the giant interface. Instead of having a function that handles each thing (size, font, color, what-to-display, etc...) have a singular function that accepts a "role" and data that represents the role. This requires some sort of wrapper that can contain multiple data types.
QT's QAbstractItemModel Class Reference has a good example:
QVariant QAbstractItemModel::data ( const QModelIndex & index, int
role = Qt::DisplayRole ) const [pure virtual]
What that function will do is return the QVariant that represents the role indicated at the index provided.
The downside of this approach, is you have to know what roles exist, and what they do. QT's default roles are shown here.
I like to have parts of the model able to instrument themselves:
class Model {
private:
int value;
public:
void instrument(Instrumenter& instrumenter);
};
The Instrumenter manages the creation of controls. The model will tell it how it can be controlled and give it access to the data.
void Model::instrument(Instrumenter& instrumenter) {
instrumenter.addRangeController(0, 100, 5, value);
}
Then for different input devices (e.g keyboard, touchscreen) you can create appropriate controls:
class KeyboardInstrumenter : public Instrumenter {
public:
void addRangeController(int min, int max, int increments, int& controlled) {
// create 3 widgets, up arrow, down arrow, and value
}
};
class TouchscreenInstrumenter : public Instrumenter {
public:
void addRangeController(int min, int max, int increments, int& controlled) {
// create slider with min, max and increments
}
};
Instead of passing in the int directly we could have wrapped it in a controlling object, to aid encapsulation.

Configuring new document in MFC

When the user creates a new document in my SDI-application, I need to present a dialog specifying details on the document to be created (think: resolution, bit-depth, etc.) I initially put the code for displaying this dialog in OnNewDocument() (I don't need it when opening an existing document), but putting user-interface code in the document-class just doesn't feel right (also, I don't have any CWnd* to use as a parent for the dialog).
Is there a better place to do this in MFC?
You're right, the document class is no good place for UI.
CDocTemplate::[OpenDocumentFile][1](pszPath) looks like a better candidate:
pszPath==NULL means 'create a new document'.
The method is virtual -> Just derive CMySingleDocTemplate from CSingleDocTemplate and use an instance of this class in CMyWinApp::InitInstance().
This class is responsible for creating docs, frames and views, hence I think it's a good place to put a UI operation.
BOOL CMyWinApp::InitInstance()
{
...
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CMySingleDocTemplate( // <--Derives from CSingleDocTemplate
IDR_MAINFRAME,
RUNTIME_CLASS(CMyDoc),
RUNTIME_CLASS(CMainFrame),
RUNTIME_CLASS(CMyView));
AddDocTemplate(pDocTemplate);
...
}
CDocument* CMySingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName,
BOOL bMakeVisible)
{
CDocument *pDoc =
CSingleDocTemplate::OpenDocumentFile(lpszPathName, bMakeVisible);
if (lpszPathName==NULL)
{
// GUI to get user info
// update doc
m_pOnlyDoc->Blah(input);
// update view
m_pOnlyDoc->UpdateAllViews(NULL,...,...);
}
}
This might not be ideal though: In SDI, there is one and only doc object. It's re-used accross File/Load and File/New operation.
This function will then be called a first time before the initial mainframe is created. You may not want to have a dialog presented to user before the frame is created. Ouch! It's a little more complicated:
Instead of popping up a GUI in in OpenDocumentFile(NULL) as above, just post a custom message/command to the main frame. Then add a handler that will react by the sequence pop up GUI/update doc/update views. That way, the main frame will be displayed before the GUI is popped up and your user will be happier.
This also solves your problem where you don't have a CWnd parent: the main frame is already created and your dialog will use it byt default.
BTW, another solution consists in adding a command handler for ID_FILE_NEW in your CMyWinApp's message map and add your own override of OnFileNew(). But when you write OnFileNew(), I believe you'll quickly find out that it's an ugly solution :-(