Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Best practice when decoupling logic and user interface



  • I am creating an application which is being 100% coded without the use of the Qt Designer for any of the user interface. I have little knowledge when it comes to creating GUI applications but I am aware that I should be using a model/view pattern and that I should separate the logic and the user interface.

    Now the issue I have is that I am not completely certain where the line is drawn between the two when it comes to Qt. Am I correct in saying that I would handle all of the button clicks etc in the same file as the UI? but then if a button click were to do something more complex I would put that code into a separate file and connect them?

    It would be great if someone could give me some clarification on this as it's simple but I am struggling to get my head round it for some reason.


  • Moderators

    @AaronKelsey said in Best practice when decoupling logic and user interface:

    Now the issue I have is that I am not completely certain where the line is drawn between the two when it comes to Qt. Am I correct in saying that I would handle all of the button clicks etc in the same file as the UI? but then if a button click were to do something more complex I would put that code into a separate file and connect them?

    Yes, that's right. The aim is usually for the UI to do only the minimal processing it has to do, and the rest is left to "business logic".

    In practice, of course, this is not so rosy. There are occasions where it is indeed very hard to ascertain what is the best way to go (for example, when creating dialogs).

    Also, serious decoupling is usually more expensive (it takes more time to do a cleanly separated code) - so for a one-off, simple projects I'd risk saying that it is OK not to decouple.

    In most cases though, benefits outweigh the drawbacks. With decoupled code it's easier to use different threads to do certain tasks, it's easier to swap the UI when necessary, and it's easier to support multiple UIs (like separate UI for mobile and desktop devices).

    Some very general hints:

    • using QML makes it harder to mix logic (C++) and UI (QML) code. With widgets it's a bit harder because everything is in C++, so the temptation to be lazy is bigger :-)
    • you can put your business logic in a library. Then the border between UI and logic becomes very clear and harder to break
    • use signals and slots extensively - they help in keeping objects separate

Log in to reply