Skip to content
  • MVC Example in Qt

    Solved General and Desktop
    3
    0 Votes
    3 Posts
    3k Views
    kshegunovK

    @Rohith

    A controller is simply an object that controls both the model and the view. The following brief example should get you started:

    class MyController : public QObject { Q_OBJECT public: MyController(QObject * parent = NULL) : QObject(parent) { view.setModel(&model); } int exec() { view.show(); return QApplication::exec(); } private: // ... QTreeView view; QFileSystemModel model; };

    And you use simply by creating the object and invoking the appropriate method(s).

    int main(int argc, char ** argv) { QApplication app(argc, argv); MyController controller; return controller.exec(); }

    @asanka424

    However in my experiece, MVC cannot be implemented as cleanly as in a web application for a desktop application. Main reasone is that all UI widgets have some sort of controller embedded in already.
    For that reason Qt has something called Model-View architecture which is not the MVC pattern but something similar to de-couple your data from the view.

    Qt only applies the view as controller, but doesn't actually "require" the user programmer to follow. The same effect as and I'd say better could be obtained by separating the logic. One thing that springs to mind: no need to derive a whole class only to have a form initialized in the constructor.

    The only problem with MVC is that it's used with and without reason (as all "architectural" and "design" patterns are), because people are mislead to believe them as one size fits all solution.

    Kind regards.