daj
daj

Reputation: 7183

Qt : which class should connect() signals and slots - inside or outside the view class?

Following good MVC practices, where should the signal slot connection happen? I feel like it should be outside the view class, possibly in a dedicated controller class that has pointers to the view and model objects.

This raises a complication though, lots of signals may come from objects within the view class (such as a QPushButton). This means I have to allow the controller to break the interface of the view class and access its members in order to set up the connect(). The alternative is to connect() things in the view class, but then it's directly interfacing with the Model class, which defeats the purpose of trying to separate them through MVC.

Upvotes: 3

Views: 2315

Answers (1)

One of the purposes of object-oriented design is encapsulation. To the user of the view class it is irrelevant how you implemented the class. The design should focus on a convenient interface first. You can then have one implementation that uses widget controls, another can be ncurses-based, yet another can use QML, etc. This means that ideally nothing about the class's insides should be visible at the level of the interface.

The whole point of the signal-slot mechanism was, in fact, decoupling the classes involved in the connections: the classes being connected need to know nothing about each other. It is thus a sensible starting point, and indeed usually correct, to set up the connections from outside of the classes.

To help you in this task, you can leverage the signal-signal connections. In Qt, a signal is just a method whose implementation is machine-generated. It has a different designation in the metadata, but it is an invokable method just as a slot is. So, when considered as a target of a connection, the signals and slots are equivalent. You can connect signals to signals. A signal-signal connection simply invokes the target signal method when the source signal method is invoked.

Upvotes: 3

Related Questions