Writing QML Application in a Flux way


  • Qt Champions 2016

    (Edit: A new version of this article is available on Medium. It comes with better diagram , example code and explanation.

    Action-Dispatcher Design Pattern for QML — Medium
    )

    After coding QML for a year, I think QML is a great concept. However, it is not a perfect solution. There still has plenty of room for improvement. On the other hand,I also think about can I write QML in a better way.

    The first problem is testability. How can I write test code in a more easy way?

    The second problem is writing clean code. Generally speaking, break down big QML file into smaller files should be more readable and reusable. But it is not always true. I found that I did a lot of copy & paste in .qml file for signal propagation / property passing. Refactoring is very troublesome.

    Finally, I come up with an idea inspirited by React’s Flux Application Framework. I would like to share my idea of writing QML application in Flux way. Any suggestion of this idea will be highly welcomed.

    The Problem

    Signal propagation in QML can be troublesome. Let’s take a simple example. Suppose you have a list of item, each item has a delete button to remove it from the list. Once it is pressed, it will show a confirmation dialog.

    Hierarchy :

    YourWindow.qml -  YourListView.qml - YourItem.qml
    

    Usually you should avoid making a super big QML file by down break component into separate files to keep it simple and reusable. However, sometimes it do not simplify the architecture due to signal propagation.

    YourItem should be the component that receive mouse event. But what component should prompt a dialog and perform removal? YourListView.qml? YourWindow.qml?

    YourListView.qml :

    ListView {
       delegate: YourItem {
           onRemoveClicked: alertDialog.open();
       }
    }
    

    or

    YourListView.qml (Signal Propagation) :

    ListVIew {
      id: listView
       signal removeClicked(int index);
       delegate: YourItem {
           onRemoveClicked: listView.removeClicked(model.index);
       }
    }
    

    And then imaginary you got a new requirement: "Press on an item to launch another window."

    Obviously, it is not duty of YourListView. And probably it will become:

    ListVIew {
       id : listView;
       signal removeClicked(int index);
       signal clicked(int index);
       delegate: YourItem {
           onRemoveClicked: listView.removeClicked(model.index );
           onClicked: listView.clicked(model.index);
       }
    }
    

    More and more signal will be added in product life cycle. (e.g Sorting, Edit, Clone, tag ….) It is fine if you don’t refactor the code. Otherwise, you should be aware of breaking a working function.

    What happen if you are asked to add a TabBar to hold multiple list? The filtering rule of list in each tab is different.

    Hierarchy:

    YourWindow.qml -  YourTabBar.qml - YourListView.qml - YourItem.qml
    

    YourTabBar.qml:

    TabBar {
      id: tabBar
       signal removeClicked(string id);
       signal clicked(string id);
    
       Tab {
         ListView {
             onRemoveClicked: { tabBar.removeClicked(id); }
             onClicked: { tabBar.clicked(id) };
         }
       }
    
       Tab {
         ListView {
             onRemoveClicked: { tabBar.removeClicked(id); }
             onClicked: { tabBar.clicked(id) };
         }
       }
    }
    

    It is just too terrible! Too many C&P codes there!

    An alternative approach to solve this problem is passing reference of YourWindow component or callback to YourItem and let its execute directly. But that means you still need to pass the value from YourWindow to YourItem via YourTabBar and YourListView. And YourItem can not be used out of YourWindow.

    Therefore, I would like to propose another method inspired by Facebook’s React Flux Application Framework.

    What is Flux Application Framework?

    Flux | Application Architecture for Building User Interfaces

    In Flux Application framework, have three major parts: the dispatcher, the stores, and the views (React components). Controller do not existed in Flux application.

    "Flux eschews MVC in favor of a unidirectional data flow. When a user interacts with a React view, the view propagates an action through a central dispatcher, to the various stores that hold the application's data and business logic, which updates all of the views that are affected. This works especially well with React's declarative programming style, which allows the store to send updates without specifying how to transition views between states."

    Actions
    "The dispatcher exposes a method that allows us to trigger a dispatch to the stores, and to include a payload of data, which we call an action. The action's creation may be wrapped into a semantic helper method which sends the action to the dispatcher. For example, we may want to change the text of a to-do item in a to-do list application."

    Architecture:

    Architecture

    View component read from Store but do not write to it directly. It ask Action to do so. The data flow is unidirectional.

    Architecture

    The “Action” component is in fact a singleton component which is accessible from anywhere in the code. Usually it just provide helper function to send message to Dispatcher.

    A store can response to multiple messages. A message may also be processed by multiple stores. It is very flexible.

    So how Flux application framework could improve our code?

    First of all, we could declare an ItemAction singleton component.

    ItemAction.qml:

    pragma Singleton;
    
    QtObject {
     function open(id) { AppDispatcher.dispatch(“ItemOpen”, { id : id })  };
     function remove(id) { AppDispatcher.dispatch(“ItemRemove”, { id: id})  }
    }
    

    The ItemAction component provides a set of helper functions to dispatch message. But it has no knowledge about receiver.

    As it is singleton component, it could be called in anywhere. So YourItem may call its method directly.

    YourItem.qml:

    Item {
      Button {
        onClicked: ItemAction.remove(id);
      }
      Button {
        onClicked: ItemAction.open(id);
      }
    }
    

    Receiver can be anywhere too. Dependence is not a matter.

    YourWindow.qml

    Connections {
       target: AppDispatcher
       onDispatched : {
        if (name === “ItemRemove”} { /// do something
       } else if (name === “ItemOpen” } {
       }
      }
    }
    

    The signal propagation flow before using Flux Application Framework
    Before Using Flux

    The signal propagation flow after using Flux Application Framework

    After Using Flux

    Remarks : Dispatcher is not shown in the above diagram. Because you don’t need to modify dispatcher to add signal.

    The immediate benefit of using Flux is the removal of unnecessary signal propagation / property passing.

    So how about Store? It is not shown in the above example.

    Since QT support data binding for every component derived from QObject. A delegated store component may not be necessary. A QML item can be a mixture of store / model / view. How to use the data received from Dispatcher should be up to programmer’s choice.

    Therefore, architecture may become:

    architecture.png (353×182)
    Architecture of Action-Dispatcher design pattern for QML.

    Conclusion

    Pros

    • Clean up code by remove unnecessary signal propagation and property passing.
    • Loose coupling design. Refactoring is easy.
    • Better code reuse
    • Your code is more testable via the Action component.

    Cons

    • You need to declare Action components before use it. Sometimes it is overkilled solution for a problem.

    An implementation of Dispatcher is available at : benlau/quickflux

    What do you think about this approach? Any question / feedback is highly welcomed.



  • "Architecture of Action-Dispatcher design pattern for QML" could be a nice title for a book by the way... :)


  • Lifetime Qt Champion

    Hi,

    Looks pretty interesting ! Did you try to submit that to the Qt devs ?


  • Qt Champions 2016

    @SGaist Should be interesting. But I never tried to submit. Where should I submit to?


  • Lifetime Qt Champion

    I'd start on the interest mailing list


  • Qt Champions 2016

    QuickFlux v1.0.1 has been released.

    Changes:

    AppListener

    Added new properties, “filter” and “filters”. Once it is set, only message with name matched will emit “dispatched” signal.

    By using “filter" property, users could write their listener in a more simple way:

    New Method:

    AppListener {
        filter: “NewItem"
        onDispatched: {
           // Code to handle “NewItem” message here.
       }
    }
    

    Old method:

    // Listen for multiple messages.
    AppListener {
        onDispatched: {
            switch (name) {
                case "messageType1":
                    // ...
                    break;
                case "messageType2":
                    // ...
                    break;
            }
        }
    }
    

    `
    or

    AppListener {
    
      Component.onComponented: {
        on("messageType1",function() {
           /// Your code here.
        });
        on("messageType2",function() {
           /// Your code here.
        });
      }
    }
    


  • thanks for posting this.

    in the qmlunittests main.cpp references
    #include <QtQuickTest/quicktest.h>

    but i can't find it in the https://github.com/benlau/quickflux project.
    do you have an example app ?



  • @clogwog The qmlunittests program is an test suite to verify the correctness of the program. Things like header of "<QtQuickTest/quicktest.h>" is not needed in your program. So you may just ignore this folder.

    Instead, I just made an example program to demonstrate how to use it:

    quickflux/examples/todo at master · benlau/quickflux

    Please feel free to ask if you have any questions.



  • Great article. Thanks. This will help me a lot.



  • @Ben-Lau thank you for the example ! it will help a lot.


  • Qt Champions 2016

    v1.0.3 has been released.

    Changes:

    New Components

    1. AppScript

    AppScript is a helper component to handle asynchronous sequential workflow. The immediate benefit of using AppScript is the centralisation of code in a place. Instead of placing them within onXXXX code block in several components in several places.

    1. AppListenerGroup

    AppListenerGroup collects listener ID from all of its child AppListener and initialize their waitFor property.
    It could be used as the base type of a Store component for setup dependence between them.

    MyStore1.qml

    AppListenerGroup {
        AppListener {
        }
        AppListener {
        }
    }
    

    MyStore2.qml

    AppListenerGroup {
       waitFor: MyStore1.listenerIds
    }
    

    Changes

    AppDispatcher

    1. Added addListener() function

    Registers a callback to be invoked with every dispatched message. Returns a listener ID that can be used with waitFor().

    1. Added removeListener() function

    Remove a callback by the listenerId returned by addListener

    1. Added waitFor() function

    Waits for the callbacks specified to be invoked before continuing execution of the current callback. This method should only be used by a callback in response to a dispatched message.

    AppListener

    1. Added “listenerId” property

    The listener ID of this component. It could be used with AppListener.waitFor/AppDispatcher.waitFor to control the order of message delivery.

    1. Added “waitFor” property

    If it is set, it will block the emission of dispatched signal until all the specified listeners invoked.

    Example code:

    AppListener {
      id: listener1
    }
    
    AppListener {
      id: listener2
      waitFor: [listener1.listenerId]
    }
    


  • Hi Ben,

    Thank for your contributions!

    Did you discuss about writing QML Application in a Flux way with developers of Qt via Qt development mailing list?

    If not, why not?

    Merry Christmas!


  • Qt Champions 2016

    @Vincent007 no. hmmm... Just I can't think of any reason to send to dev mailing list. Ask them for comment? or ask them to include related class in next version? Ofcoz it will be better if more people can comment / raise suggestion, but I just not sure should I send to dev mailing list.

    Merry Christmas!



  • Hi Ben,

    I think your work can help Qt developers think how QML should be evolved in feature. Therefore you can discuss with them about the evolution of QML by your work.


  • Qt Champions 2016

    @Vincent007 hmm. Let's me think about it. By the way, I am going to publish another article with similar topic but better explanation, code and diagram on a blog in this week.



  • Hi Ben,

    i'm not sure if this is a bug but i'm trying to figure out how to use quickflux by making a small change to the todo example.

    I added a 'mark all items done' button and mark all items as done. however the ui doesn't always update.

    example: 1) start application (3 items in list 1 in done)
    2) press 'all done' -> all items disappear (expected)
    3) show all items by checking 'show completed' (expecteD)
    4) unmark one item (for example 'Task A')
    5) press 'all done' -> 'Task A' doesn't update to done ?

    if i uncheck and re-check 'show completed' the model and view are back in sync.

    https://github.com/clogwog/fluxtest1

    am i missing something ?


  • Qt Champions 2016

    @clogwog I can't reproduce your problem in my example program and in your code. When it is set to "Show Completed". It will show every tasks. So if you set a task done in "Show Completed" mode. It won't disappear. The behaviour should be correct.



  • no, i was expecting it to show all tasks as you said, i just expected it to switch back to checked when i pressed the 'all done' button

    so when you are in the 'show completed' mode in step 5 with a task you just set to 'uncompleted' and then press 'all done' your tasks goes back to checked ?



  • @benlau

    Hi Ben,

    Thank for your sparking idea about this area, It's charming & meaningful to do this.
    BTW, could U show the link of Ur another article with better description if possible.

    Thanks !

    Happy New Year !


  • Qt Champions 2016

    @clogwog said:

    no, i was expecting it to show all tasks as you said, i just expected it to switch back to checked when i pressed the 'all done' button

    so when you are in the 'show completed' mode in step 5 with a task you just set to 'uncompleted' and then press 'all done' your tasks goes back to checked ?

    oh, you mean in your program. I didn't realize that you have added a "All Done" button. The problem is about data binding in Qt. Qt use one-way data binding. Although it has binded CheckBox.checked to model.done , the binding will lost whatever it is toggled by user event. It is overridden by system. And that is why step 5 failed.

    You may solve this problem in this way:

    At TodoVisualDataModel.qml:

        delegate: TodoItem {
            id:item
            uid: model.uid
            title: model.title
            property bool done: model.done
    
            onDoneChanged: {
                checked = model.done;
            }
    
            Component.onCompleted: {
                item.VisualDataModel.inNonCompleted = Qt.binding(function() { return !model.done})
            }
        }
    

    @benevo: thx. The article is not ready yet. I will post it within this few days.



  • @benlau thank you for taking the time to tell me this !
    i have learned something new.

    kind regards,
    tom



  • nice,thanks for share,i think MVC is too good for our Qml project.


  • Qt Champions 2016



  • @benlau

    Do you think it is beneficial to use Action-Dispatcher Design Pattern in C++ ?
    If Yes, would you mind giving us an example in C++ ?


  • Qt Champions 2016

    @Vincent007 yes, I think so. However, I am not coding in pure C++ way. I could provide a C++ and QML mixing example code. Before it is ready, you may take a look about the C++ API of QuickFlux:

    QFAppDispatcher Class | QuickFlux 1.0



  • @benlau Thank for your new example in advance!

    I think it is time to show your work to Qt contributors via Qt development mailing list. I think your work can help Qt contributors think how QML should be evolved in feature.



  • Someone implemented FLUX too!


  • Qt Champions 2016

    @Vincent007 Interesting. thx.

    I am happy to see more people talking about using Flux in Qt/QML even they are not using my library. That means the approach really works. Moreover, until now, I don't see a standard QML application guide available yet. I would like to draw more attention from Qt users / developers to think about this problem.

    p.s I have added a FAQ about why it need a Dispatcher instead of just a QObject:

    Why use AppDispatcher instead of listening from AppActions directly?


  • Qt Champions 2016

    v1.0.4 has been released.

    New Components

    KeyTable

    KeyTable is an object with properties equal to its key name. Once it's construction is completed, it will search all of its string property. If it is a string type and not assigned to any value, it will set its value by its name. It can be used to create ActionTypes.qml in QuickFlux Application.

    Example:

    KeyTable {
    
        // It will be set to "customField1" in Component.onCompleted callback.
        property string customField1;
    
        // Since it is already assigned a value, KeyTable will not modify this property.
        property string customField2 : "value";
    
    }
    

    Filter

    Filter component listens for the parent's dispatched signal, if a dispatched signal match with its type, it will emit its own "dispatched" signal. Otherwise, it will simply ignore the signal.

    This component provides an alternative way to filter incoming message which is suitable for making Store component.

    Example:

    pragma Singleton
    import QtQuick 2.0
    import QuickFlux 1.0
    import "../actions"
    
    AppListener {
        id: store
    
        property ListModel model: ListModel { }
    
        Filter {
            type: ActionTypes.addTask
            onDispatched: {
                model.append({task: message.task});
            }
        }
    
    }
    

    It is not suggested to use nested AppListener in a Store component. Because nested AppListener do not share the same AppListener::listenerId, it will be difficult to control the order of message reception between store component.

    In contrast, Filter share the same listenerId with its parent, and therefore it is a solution for above problem.

    Changes

    AppScript

    1. Added "autoExit" property

    examples/todo

    1. Migrated to use KeyTable and Filter
    2. Added StoreAdapter to demonstrate how to use "waitFor" between stores.

    StoreAdapter.qml

    import QtQuick 2.0
    import "../stores"
    
    Item {
    
        Component.onCompleted: {
            TodoStore.waitFor = [UserPrefsStore.listenerId];
        }
    
    }
    

  • Qt Champions 2016

    QuickFlux v1.0.5 has been released.

    New Component

    ActionCreator

    ActionCreator is a component that listens on its own signals, convert to message then dispatch via AppDispatcher. The message type will be same as the signal name. There has no limitation on number of arguments and data type.

    For example, you may declare an ActionCreator based component as:

    import QtQuick 2.0
    import QuickFlux 1.0
    pragma singleton
    
    ActionCreator {
      signal open(string url);
    }
    

    It is equivalent to:

    import QtQuick 2.0
    import QuickFlux 1.0
    pragma singleton
    
    Item {
       function open(url) {
         AppDispatcher.dispatch(“open”, {url: url});
       }
    }
    

    Changes

    QFAppDispatcher

    1. Added dispatch(const QString &type, const QVariant& message) member method for C++ to dispatch message.

  • Qt Champions 2016

    v1.0.6 has been released

    New Component

    1. Object - It is a QtObject that able to hold children component.

    Changes

    1. Filter

    a) Now it could listen from any component that has "dispatched" signal

    Item {
      signal dispatched(string type, var message)
    
      Filter {
        type: ActionTypes.addItem
        onDispatched: {}
      }
    }
    
    

    b) Support to hold children item

    Filter {
      Promise {
      }
    }
    

    c) Added "types" property to filter multiple types of action

    Filter {
      types: [ActionTypes.addItem , ActionTypes.removeItem]
    }
    

    2. ActionCreator

    a) Added "genKeyTable()"

    According to the registered signal in the ActionCreator object, it could create a key table (ActionTypes) in QML.

    3. KeyTable

    a) Added getSourceFile()/genHeaderFile() - Generate a C++ header and source file for this KeyTable object.

    Bug Fix:

    1. [QTBUG-58133] Crash on emitting a signal from C++ to QML with undefined QJSValue - Qt Bug Tracker

    2. qmlRegisterType under MSVC goes nuts · Issue #7 · benlau/quickflux

    Preview of Quick Flux 1.1

    As a preview of new components in v1.1, they are also included in this release. But the API is not frozen. It may change in the official release.

    1. Dispatcher - non-singleton Dispatcher
    2. MiddlewareList / Middleware - a mechanism to extend the functionality of dispatcher allowing for advanced asynchronous workflow and integration with visual component like FileDialo
    3. Store - A replacement of AppListener
    4. Hydrate - Serialize and deserialize a store to/from a JSON object.

  • Qt Champions 2016

    v1.1 has been released!

    Detailed explanation:

    What is new in Quick Flux 1.1?

    New Features

    1. Support Non-singleton dispatcher.

    2. Middleware - a mechanism to extend the functionality of dispatcher allowing for advanced asynchronous workflow and integration with visual component like FileDialog.

    3. Store - A replacement of AppListener that could listen from non-singleton dispatcher, and re-dispatch the action message to another Store components sequentially. It could avoid the over-complicated waitFor mechanism.

    4. Hydration - Serialize and deserialize a store to/from a QVariantMap object.

    New Components

    1. MiddlewareList & Middleware

    2. Store

    3. Hydrate

    See Class Document for details

    Bug Fix

    https://bugreports.qt.io/browse/QTBUG-58133

    Reference

    What is new in Quick Flux 1.1?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.