Access CPP of the ListView in QML function

ListView {
            id: listView
            dataModel: dataModel
            listItemComponents: [
                ListItemComponent {
                    type: "item"
                    StandardListItem {
                        title: ListItemData.title
                        description: app.formatDate(ListItemData.pubDate);
                    }
                }
         ]
}

and in the PRC

QString ApplicationUI::formatDate(QString date) {
    return "bla";
}

Function call leave outer ListView works well, but I cannot access any function defined outside ListView!

In this case, I get asset:///blabla.qml:16: ReferenceError: can't find variable: app

How can I call it?

For some strange reason the listItemComponents are outside the normal code flow. But you can bypass. Give your listItemComponent a name/id. You can reference it trough the parent ListView. Something like this should work:

StandardListItem {
 id: mscurli
 title: ListItemData.OriginalTitle;
 description: ListItemData.TheatreAndAuditorium
 status: mscurli.ListItem.view.getShowTime(ListItemData.dttmShowStart);
}

I used a set inside my ListView simple helper function to get the C++ code:

function getShowTime(str) {
 return _myapp.formatTime(str);
}

Tags: BlackBerry Developers

Similar Questions

  • How to get the item to the index by the listview in qml programming

    Hi guys.

    I'm sorry my English not good level.

    At the point of selection Android listview to index easylly, I call ListView.selectionPosition (int index)

    But when you use ListView on cascades qml, I think point get in way to the index.

    Hope you help me.

    For a simple DataModel with a single level of items, you can access the item at a specific position with code of God:
    int position = 0
    var MonElement = myDataModel.data ([position])-requires one [of QVariantList]

  • How get the number of items in the ListView inside QML?

    QML/JavaScript newbe question here please.

    Suppose I have .qml

    import bb.cascades 1.0
    
    NavigationPane {
        id: navigationPane
        Page {
    ...
            Container {
    ...
                  ListView {
                        id: listviewPlayers
    ...
    

    and I want to do something if ListView does contain all of the elements

        onCreationCompleted: {
            // this slot is called when declarative scene is created
            if (listviewPlayers.AllItems.count() == 0){
                // do something;
            }
    

    but when I run the present I get complain AllItems is not defined in this line:

     if (listviewPlayers.AllItems.count() == 0){
    

    What I doing wron? I can do the same thing in C++ without any problem.

    Thank you.

    Oh, this thing AllItems seems to be a 'Sentinel' or a magic value used in special cases, unrelated to this.

    I think that ListView manages all this, but defers everything to do with the pieces of data to the model, you don't have to go to the model for the data. ListView knows how VisualNodes (the components list item) he created at the time of the display on the screen, but also have to tell you the total number of elements in the model would simply duplicate work. (The reasoning behind this interpretant.)

  • How to refresh the listview that is in another function

    Hi all,
    I have a problem with a refreshing of the listview.

    I have 3 features in the application, let's say 'feature A' 'feature B' and 'C'.

    I also have 2 tables and sqlite db (local) .and 1 view their names are 'A table', 'table B' and 'see C.

    View C is like this:

    create view C as

    Select a.oneColumn

    Table has a

    Union

    Select b.oneColumn

    Table B b;

    Each function has the main amx.page and each of them has listview values from the (local) sqlite DB.


    According to A, I can add new row to the database (line update or delete) and the list is updated with the help of the "ProviderChangeSupport".

    Same thing happens in the function (B) everything is ok so far. But according to C, there also listview. When I delete operation or update functionality or B.

    the listview in C function is not updated.


    I hope you all can easily understand the problem and help me with the solution. Oracle Mobile Application Framework.

    Hello

    you need to reset a feature - navigating it--you want to ensure the functionality and so refreshes the view. The change of supplier support works in the ClassLoader (feature film) it is issued to. You can use a listener to refresh the controls collection of data used by a list, but it does not work automatically.

    Frank

  • Can not access the context in QML property

    So I have an arraydatamodel in the CPP file, I use qml-> setContextProperty (...) to set it up to allow QML to access, the strangest part is, no matter if I put it in navigationPane Page or a container, it keeps saying can't find not variable, but in the same QML in ListView, they can access it without a problem. The other weird part, it is an another QML is able to access it in the tag of the page, the same model.

    By default of the Jun 02 9000 REVIEWS asset:///main.qml:24 09:12:59.416 com.example.IntervalTimer1.testDev_ervalTimer1a7a2c2e2.427733134: ReferenceError: can't find variable: eventsModel
    By default of the Jun 02 9000 REVIEWS asset:///main.qml:110 09:12:59.416 com.example.IntervalTimer1.testDev_ervalTimer1a7a2c2e2.427733134: ReferenceError: can't find variable: eventsModel

    Here is my code

    import bb.cascades 1.0
    
    NavigationPane {
        id: navigationPane
        backButtonsVisible: false
        // Javascript definition
        function udpateTotalTimeLabel() {
            console.log("In updateTotalTimeLabel function");
            var totalHour = 0, totalMinute = 0, totalSecond = 0;
            // To debug javascript object print function
            var print = function(o) {
                var str = '';
    
                for (var p in o) {
                    if (typeof o[p] == 'string') {
                        str += p + ': ' + o[p] + '; 
    '; } else { str += p + ': {
    ' + print(o[p]) + '}'; } } return str; } console.log("EventsModel: " + eventsModel.size()); for (var i = 0; i < eventsModel.size(); i ++) { var currentEvent = eventsModel.data([ i ]); console.log("EventsEvent: " + currentEvent["EventName"]); totalHour += currentEvent["EventHour"]; totalMinute += currentEvent["EventMinute"]; totalSecond += currentEvent["EventSecond"]; } if (totalHour < 10) totalHour = "0" + totalHour; if (totalMinute < 10) totalMinute = "0" + totalMinute; if (totalSecond < 10) totalSecond = "0" + totalSecond; totalTimeLabel.text = totalHour + ":" + totalMinute + ":" + totalSecond; } function onDataReady() { console.log("Received DataReady signal"); navigationPane.udpateTotalTimeLabel(); newEventSheet.close(); } Page { id: root titleBar: TitleBar { title: "Interval Timer" } ..... onCreationCompleted: { navigationPane.udpateTotalTimeLabel(); console.log("No of EventsModel: " + eventsModel.size()); console.log("In sheet creationCompleted"); mainObj.dataReady.connect(navigationPane.onDataReady); } }

    In the PRC

    // Default empty project template
    #include "applicationui.hpp"
    
    #include 
    #include 
    #include 
    #include "CountdownTimer.hpp"
    
    using namespace bb::cascades;
    
    ApplicationUI::ApplicationUI(bb::cascades::Application *app)
    : QObject(app)
    {
        // create scene document from main.qml asset
        // set parent to created document to ensure it exists for the whole application lifetime
        QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
    
        // Initialize the Array Data Model for holding events
        this->eventsModel = new ArrayDataModel();
        // For Testing only
        QVariantMap event;
        event["EventName"] = "Event1";
        event["EventHour"] = "00";
        event["EventMinute"] = "01";
        event["EventSecond"] = "02";
        this->eventsModel->append(event);
    
        // create root object for the UI
        AbstractPane *root = qml->createRootObject();
    
        // Registering the QTimer type to QML
        qmlRegisterType("TimerLibrary", 1, 0, "CountdownTimer");
    
        // Setting the access for QML to member variable
        qml->setContextProperty("eventsModel",this->eventsModel);
        qml->setContextProperty("mainObj",this);
    
        // set created root object as a scene
        app->setScene(root);
    }
    
    .....
    
    void ApplicationUI::refreshData()
    {
        emit dataReady();
    }
    

    Thank you.

    The fixed.

    You must call setContextProperty before calling createRootObject.

  • To access the values from the row outside the ListView ListItem

    Hello

    I spent two hours browsing the forums and documentation with no chance of finding a solution on how to access the list item data from outside the listview.

    Let explain me my code. It is marked with I work and what does not work and its expected behavior.

    Should work behavior


    Tapping & getting data

    The arrayDataModel is filled with 4 rows. Firstly the list item, second item in the list... etc.

    • Tapping on the order of the day, label with the id of triggeredText displays the value of a threaded list item.
    • The index of the tapped icon appears in the label with the id of triggerredIndex.

    Incrementing Index using ActionItems onBar

    By pressing action items 'previous' and 'next', you can increment the index value to the label with the id of triggeredIndex. The order of the index is 0-4, even as total of the items in the list.

    How to extract data from the index when the value of triggeredIndex?

    Buttons

    The buttons at the bottom of the screen... Select 1, select the 2nd, 3rd Select should select indexes 0,1,2 of the list and display the value in triggeredText and triggeredIndex. They do not work.

    How did I pull the values when you click the buttons?

    import bb.cascades 1.3
    
    TabbedPane {
        id: root
        showTabsOnActionBar: false
    
        Tab {
            id: mainTab
            title: "Test List"
                Page {
                    id: mainPage
                    titleBar: TitleBar {
                        title: "List Traversal Test"
                    }
                    actions: [
                        ActionItem {
                            title: "Previous"
                            ActionBar.placement: ActionBarPlacement.OnBar
                            onTriggered: {
                                // get current selected index from list=
                                var currentIndex = parseInt(triggeredIndex.text);
    
                                if(currentIndex <= 0){
                                    //do nothing already at first item
                                }else{
                                    // subtract 1 from index ( ci - 1) ?
                                    var newIndex = parseInt(triggeredIndex.text) - 1;
    
                                    // show data from new selected index
                                    // ???
    
                                    // triggeredItem.text = XXX // the data
                                    // ???
    
                                    // triggeredIndex.text = X // the current index
                                    triggeredIndex.text = newIndex;
                                }
                            }
                        },
                        ActionItem {
                            title: "Next"
                            ActionBar.placement: ActionBarPlacement.OnBar
                            onTriggered: {
                                // get current selected index from list=
                                var currentIndex = parseInt(triggeredIndex.text);
    
                                if(currentIndex == 4){
                                    //do nothing already at lastitem
                                }else{
                                // add 1 to index ( ci + 1) ?
                                var newIndex = parseInt(triggeredIndex.text) + 1
    
                                // show data from new selected index
                                // ???
    
                                // triggeredItem.text = XXX // the data
                                // ???
    
                                // triggeredIndex.text = X // the current index
                                triggeredIndex.text = newIndex;
                            }
                            }
                        },
                        ActionItem {
                            title: "Clear"
                            ActionBar.placement: ActionBarPlacement.OnBar
                            onTriggered: {
                                // set current index to 0 (top item in list)
                            }
                        }
    
                    ]
                    Container {
                        preferredHeight: maxHeight
                        layout: StackLayout {
                            orientation: LayoutOrientation.TopToBottom
                        }
    
                        Label{
                            id: triggeredItem      // value of listitem from current index
                            text: "0"
                        }
                        Label{
                            id: triggeredIndex    // current index
                            text: "0"
                            onTextChanged: {
                                // set triggeredItem.text to contents of selected ListItem with same index
                                // STUCK HERE cannot access ListItem.dataModel(indexPath) from here....
                            }
    
                        }
                        Container{
                            ListView {
    
                                id: theList
                                objectName: "dalist"
                                dataModel: ArrayDataModel {
                                    id: theListModel
                                }
                                listItemComponents: ListItemComponent {
                                    StandardListItem {
                                        id: itemRoot
                                        title: ListItemData
                                    }
    
                                }
                                onTriggered: {
                                    var si = dataModel.data(indexPath);
                                    triggeredItem.text = "LIST ITEM CONTENT: " + si;  //set content when user taps on item
                                    triggeredIndex.text = "LIST ITEM INDEX INDEX: " + indexPath;  // set index when user taps
                                }
    
                                onSelectionChanged: {
                                    //console.log(selected);
                                }
    
                                onCreationCompleted: {
    
                                    //add some data to the listview
                                    theListModel.append("First List Item");
                                    theListModel.append("Second List Item");
                                    theListModel.append("Third List Item");
                                    theListModel.append("Fourth List Item");
                                }
                            }
    
                        }
                        Container{
                            layout: StackLayout {
                                orientation: LayoutOrientation.LeftToRight
                            }
                        Button{
                            text: "Select 1st"
                            onClicked: {
                                theList.clearSelection();
                                theList.select(0);
    
                            }
                        }
                        Button{
                            text: "Select 2nd"
                            onClicked: {
                                theList.clearSelection();
                                theList.select(1);
    
                            }
                        }
    
                        Button{
                            text: "Select 3rd item"
                            onClicked: {
    
                                //expected behaviour is to show data from Third List Item
    
                                // triggeredIndex.text = INDEX 3
                                // triggeredText.text = (DATA FROM THIRD LIST ITEM)
    
                                // THIS IS NOT WORKING ....
                                theList.clearSelection();
                                theList.select(2);
                                console.log(theList.dataModel(3));
                                triggeredItem.text = theListModel.dataModel(3);
    
                            }
                        }
                    }
                   }
                }
            }//tab
    }
    

    Thank you and have a happy and healthy 2015!

    Your help will be greatly appreciated.

    I ran and got this:

    asset:///main.qml:161: TypeError: Result of expression 'theList.dataModel' [bb::cascades::ArrayDataModel(0x1091a838)] is not a function.
    

    But it works

    theListModel.data([3])
    

    But this isn't the solution, you have a more serious problem. You select a value, you trigger. If you add this in onTriggered you select it (and you can see that it changes color when it is selected).

    theList.select(indexPath);
    

    If you want to use option to deselect

    theList.select(indexPath, !theList.isSelected(indexPath));
    

    And if you want to have that one chose this

    theList.clearSelection();
    theList.select(indexPath);
    

    Inside the button 'Select the 3rd point' allows to select programmatically

    theList.select([2]);
    

    It works but I'm not sure what you're trying to do

  • To access the properties of QML context through several QML files

    It seems so basic, but I don't see how well...

    I put a 'WebAPI' context property to access my class that makes HTTP requests etc. WebAPI works very well main.qml, but when I try and use it in the included LargeThumbItem.qml I get:

    "LargeThumbItem.qml:37: ReferenceError: can't find variable: WebAPI.

    How to set a context property that is available for * all * my QML files? What is the best practice for this?

    hand. QML

    {

    ...

    {ListItemComponent}

    type: 'point '.

    LargeThumbItem {

    }

    }

    ....

    }

    LargeThumbItem.qml

    {

    ....

    WebAPI.getImagePath (...)

    ...

    }

    I do the usual configuration...

    QmlDocument * qml = QmlDocument::create("asset:///main.qml").parent(this);

    QML-> setContextProperty ("WebAPI", m_pWebAPI);

    I tried calling qml-> documentContext()-> setContextProperty(), but it did not work. Is there a global context that I can put all documents will inherit? (the API documentation seems to suggest there is).

    This problem is related to what is described here and the solution is the same. The problem is that the ListItemComponents have a different context and lifecylce due to the fact that they are cached in and out as the scrolls of the ListView (see here for details).

    I solved it by adding a dynamic property on the global object of 'Qt' for example in onCreationCompleted() or anywhere where the senses in main.qml. In my case, I chose to pass a string, because I don't know if the global property to the instance around WebAPI is a good idea.

    Qt.homeListBaseURL = WebAPI.getImagePath ("TitleImagePathPrefix", "170 x 240")

    Then in LargeThumbItem.qml for example

    {WebImageView}

    ...

    URL: Qt.homeListBaseURL + ListItemData.ContentId + '.jpg '.

    ...

    }

  • number of lines in the ListView blackberry stunts QML

    Hi all

    I have a ListView in QML page that contains several elements.

    I also want to display the total number of lines on the bottom of the page.

    Please tell me how.

    View the list code is as below: -.

     //! [1]
                    // The list view with all messages
                    ListView {
                        dataModel: _messages.model
    
                        listItemComponents: ListItemComponent {
                            type: "item"
    
                            StandardListItem {
                                title: ListItemData.senderName
                                description: ListItemData.sender
                                status: ListItemData.time
                            }
                        }
    
                        onTriggered: {
                            clearSelection()
                            select(indexPath)
    
                            _messages.setCurrentMessage(indexPath)
    
                            _messages.viewMessage();
                            navigationPane.push(messageViewer.createObject())
                        }
                    }
                    //! [1]
    

    Please suggest

    call on the datamodel size()

  • access to the main time line function

    Hi all

    In as2, we use _root to access the main timeline inside the movieclip or button function.

    In as3 how to access the main scenario works inside the movieclip or button.can please tell me.

    'root' is the equivalent of AS3, but use it alone will often not wortk.  Most often, you will need to cast as a form of object until the compiler will recognize.  To aid "MovieClip" (root) will usually do the trick.

  • Insert data to a specific location in the listview in blackberry 10 cascades qml?

    I have a listview with groupdatamodel, I need to insert the data into the listview at a specific location

    GroupDataModel is used for an ordered list - AFAIK you can't insert data at arbitrary positions.

    Instead, you must use one of the datamodels unordered (ArrayDataModel / QListDataModel)

  • Why can't I access object inside the ListItemComponent.onCreationCompleted C++... ?

    Hello world

    My application has a HTTP connection to retrieve the XML stream and insert data to the ListView using DataSource and DataModel, and I want to hear at each of its ListView ListItem is created and completely to use a ListItemData for my c++ object. So I write my code like this

    In main.cpp

    int main (int argc, char * argv)

    {

    App app (argc, argv);

    new MyApp (&app);)

    returnApplication::exec();

    }

    In MyApp.cpp

    MyApp::MyApp (bb::cascades:Application * app): //constructor

    {QObject (app)}

    QmlDocument * qml = QmlDocument::create("asset:///main.qml").parent(this);

    QML-> setContextProperty ("app", this);

    AbstractPane * stream = qml-> createRootObject)

    App-> setScene (NCA);

    }

    void MyApp::doMyFunction (const QString & someData) {}

    qDebug()< "yes!!="">

    }

    In main.qml
    {Page}

    {Of container

    {To ListView

    dataModel: myDataModel

    listItemComponents:]

    {ListItemComponent}

    type: 'point '.

    {Of container

    onCreationCompleted: {}

    Console.log ("-LISTITEM ONCREATION COMPLETED");

    app.doMyFunction (ListItemData.someData);    //<  but="" console="" print="" about="" "can't="" find="" variable="" "app"="">

    }

    }

    }

    ]

    } //end listview

    } //end container

    onCreationCompleted: {}

    myDataSource.load ();

    }

    attachedObjects:]

    {GroupDataModel}

    ID: myDataModel

    },

    DataSource {}

    ID: myDataSource

    Source: "some URLs to get RSS... blah blah."

    type: DataSource.Xml

    onDataLoaded: {}

    myDataModel.clear ();

    myDataModel.insertList (data);

    }

    ]

    }

    I try to run mycode. But a console is printed on "can't find variable: app". " How can I solve this problem?

    Thanks for any suggestions.
    MAZ

    Its because the listitem is not in the same document as the Page tree really, he lives with ListView and does not have direct access to the elements of the Page.

    What you can do is create a javascript function in the ListView, and then the listitemcomponent facing, which in turn can relay to your environment variable "app."

    int listitemcomponent add id: itemContainer your container can
    itemContainer.ListItem.view.someFunctionDefinedInTheListView (data)

    in the listview:

    function somefunctiondefinedinlistview (data) {}
    app.doMyFunction (data)
    }

  • [Explanation necessary] Clears the listview data and fill it again with new data

    Hello

    I correctly filled a listview in c ++, data analysed and does interesting things with it. However, I am drunk stumbling, unable to find a way delete and repopulate my display of the list...

    Question 1:

     

    1. How can after I insert data in the list view, I clear the list data and run again the same method (init) who populated the list view with the data in the first place?

    Here are the docs that I referenced and I don't understand how to implement the methods in my code.

    QList - clear() method

    https://developer.BlackBerry.com/Cascades/reference/QList.html#clear

    Using the data access Code, example
                              
    data_access/using_data_source

    GroupDataModel - Clear()

    https://developer.BlackBerry.com/Cascades/reference/bb__cascades__groupdatamodel.html#clear

    CODE

    Here is my code - filling of the display of the list of C++ and display of data in a ListView.

    MyApp.cpp

    MyApp::MyApp(bb::cascades::Application *app)
    : QObject(app){
        // create scene document from main.qml asset
            // set parent to created document to ensure it exists for the whole application lifetime
            QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
    
                AbstractPane *root = qml->createRootObject();
                qml->setContextProperty("yoyo",this);
                //grab references
                list_view = root->findChild("listView");
    
                // set created root object as a scene
                app->setScene(root);
    
                mNetworkAccessManager = new QNetworkAccessManager(this);
                bool result = connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*)));
    
                 Q_ASSERT(result);
                 Q_UNUSED(result);                 json = new QFile("data/file.json");
    }
    
    void MyApp::init(){
        QNetworkRequest request = QNetworkRequest();
         // i call some service here
         mNetworkAccessManager->get(request);
    }
    
    void MyApp::requestFinished(QNetworkReply *reply){
        qDebug() << reply->error();
        qDebug() << reply->errorString();
        if (reply->error() == QNetworkReply::NoError) {
            qDebug() << "No error";
    
                    QByteArray data = reply->readAll();
    
                    if (!json->open(QIODevice::ReadWrite)) {
                        qDebug() << "Failed to open file";
                        return;
                    }
                    json->write(data);
    
            bb::data::JsonDataAccess jda;
            QVariantMap results = jda.loadFromBuffer(data).toMap();
                    QVariantList lst = jda.loadFromBuffer(data).toList();
                GroupDataModel *m = new GroupDataModel();
                       m->insertList(lst);
                       m->setGrouping(ItemGrouping::None);
                       if(list_view) list_view->setDataModel(m);
    
        }else{
            showDialog("Boo",reply->errorString());
        }
    }
    

    MyApp.hpp

    // Tabbed pane project template
    #ifndef MyApp_HPP_
    #define MyApp_HPP_
    
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    namespace bb {
    namespace cascades {
    class Application;
    }
    }
    namespace bb {
    namespace data {
    class Application;
    }
    }
    
    /*!
     * @brief Application pane object
     *
     *Use this object to create and init app UI, to create context objects, to register the new meta types etc.
     */
    class MyApp: public QObject {
    Q_OBJECT
    public:
        MyApp(bb::cascades::Application *app);
        virtual ~MyApp() {
        }
        Q_INVOKABLE
        void init();
    private slots:
        void requestFinished(QNetworkReply *reply);
    private:
        QNetworkAccessManager *mNetworkAccessManager;
        QNetworkRequest *request;
        QFile *json;
        bb::cascades::ListView *list_view;
    };
    
    #endif /* MyApp_HPP_ */
    

    hand. QML

    import bb.cascades 1.0
    
    Page{
    Container {
                            background: Color.White
                            ListView {
                                id: listView
                                preferredHeight: maxHeight
                                objectName: "listView"
                                listItemComponents: [
                                    ListItemComponent {
                                        type: "item"
                                        Container {
                                            Container {
                                                Label {
                                                    text: ListItemData.id
                                                }
                                            }
    
                                        }
                                    }
                                ]
                                onTriggered: {
                                    console.log("selected_index: " + indexPath)
                                }
                                horizontalAlignment: HorizontalAlignment.Center
                                verticalAlignment: VerticalAlignment.Center
                            }
    
    }
    }
    

    Question 2:

    How reference to the ListView object with the name "listView" in different parts of the MyApp.cpp file? Is there anything else I should add to the header file to make the accessible listView?

    Question 3:

    What happens when you call the clear() method? How the data model is affected? How the user interface is affected? What happens in memory?

    Question 4:

    How do you verify that the data in the list has been deleted so that you can go ahead and fills again with new data? What is the cheque that I perform?

    I would also like to know how you manage multiple views of lists and data sources in your applications. Best practices or ideas?

    Thank you

    I was able to clear the listview with the following code, if anyone is interested.

    listView.dataModel = null
    

    The dataModel must be set to "null".

  • How to refresh the Listview after adding a new item

    Hello

    I have the following list:

     ListView {
                                        id: channelsList
    
                                        dataModel: categoryModel
    
                                        listItemComponents: [
                                            ListItemComponent {
                                                type: "item"
                                                StandardListItem {
                                                    title: ListItemData.name // Channel name
                                                    imageSource: ListItemData.imageFile
                                                    status: ListItemData.id
    
                                                    id: channelItemId
    
                                                    contextActions: [
                                                        ActionSet {
                                                            //title: contentView.title
                                                            ActionItem {
                                                                title: "Add to Favorites"
    
                                                                onTriggered: {
                                                                    console.log(ListItemData.id + " will be added to the Favorites");
                                                                    //categoryModel.addFavorite(ListItemData.name, ListItemData.imageFile, ListItemData.id);
                                                                    channelItemId.ListItem.view.viewTriggered(ListItemData.name, ListItemData.imageFile, ListItemData.id);
                                                                }
    
                                                            }
    
                                                        }
                                                    ]
                                                }
                                            }
                                        ]
    
                                        onTriggered: {
                                                var chosenChannel = dataModel.data(indexPath);
                                                console.log("indexPath: " + indexPath);
    
                                                var playingPage = playpagedef.createObject();
    
                                                playingPage.chname = chosenChannel.name;
                                                playingPage.cid = chosenChannel.id;
                                                playingPage.init();
    
                                                Qt.nav.push(playingPage);
    
                                        }
    
                                        attachedObjects: [
                                            // The bucket categoryModel is a non visible object so it is set up as an attached object.
                                            // The categoryModel itself is a QListDataModel defined in categorymodel.h and registered
                                            // as a type in the creation of the application.
                                            CategoryModel {
                                                id: categoryModel
                                                // The path to the JSON file with initial data, this file will be moved to
                                                // the data folder on the first launch of the application (in order to
                                                // be able to get write access).
                                                jsonAssetPath: "models/channels.json"
    
                                                // The filtering is initially set to "Category 1" to show category channels
                                                filter: label.text
                                            },
    
                                            ComponentDefinition {
                                                id: playpagedef
                                                source: "PlayingPage.qml"
                                            }
                                        ]
    
                                        function viewTriggered(name, imageFile, id)
                                        {
                                            categoryModel.addFavorite(name, imageFile, id);
                                            categoryModel.clear();
                                        }
    
                                    }
    

    and the categoeymodel.h is as follows:

    #ifndef _CATEGORYMODEL_H
    #define _CATEGORYMODEL_H
    
    #include 
    #include 
    #include 
    #include 
    
    using namespace bb::data;
    
    // The category categoryModel is based on the QListDataModel template, which in turn
    // implements the abstract DataModel class.
    typedef bb::cascades::QListDataModel CategoryListModel;
    
    /* CategoryModel Description:
     *
     * CategoryModel class for the Category List application, the data categoryModel
     * reads and write from a JSON file that keeps all item data
     * for the list.
     */
    class CategoryModel: public CategoryListModel
    {
    Q_OBJECT
    
    Q_PROPERTY(QString filter READ filter WRITE setFilter NOTIFY filterChanged)
    
    Q_PROPERTY(QString jsonAssetPath READ jsonAssetPath WRITE setJsonAssetPath NOTIFY jsonAssetPathChanged)
    
    public:
        /**
         * Constructor that sets up the recipe
         * @param parent The parent Container, if not specified, 0 is used
         */
        CategoryModel(QObject *parent = 0);
        ~CategoryModel();
    
        QString filter();
    
        void setFilter(const QString filter);
    
        QString jsonAssetPath();
    
        void setJsonAssetPath(const QString jsonAssetPath);
    
    signals:
    
        void filterChanged(QString filter);
    
        void jsonAssetPathChanged(QString jsonAssetPath);
    
    public slots:
        void addFavorite(QString channelName, QString channelImageFile, int channelId);
    
    private:
        bool jsonToDataFolder();
    
        // Property variables
        QString mFilter;
        QString mJsonAssetsPath;
        QString mJsonDataPath;
    
        // A list containing all data read from the JSON file
        QVariantList mData;
    
        //Invocation variables
        bb::cascades::Invocation* mInvocation;
    };
    
    #endif // ifndef _CATEGORYMODEL_H
    

    My problem is that the listview is not get automatically updated when a new item is added to the datamodel (a favorite channel is added). I have to exit the application and restart to see the updated list.

    categoryModel.addFavorite(name, imageFile, id);
    categoryModel.clear();
    

    categoryModel.clear ();

    does not work. I get:

    Asset: / / / hand. QML:180: TypeError: result of expression 'categoryModel.clear' [undefined] is not a function.

    I would like to know how to achieve using approach "more correct".

    QListDataModel does not expose its internal storage directly. It is possible to reconstruct the map by performing an iteration in a loop (with the help of data() and size() methods), the dataModel entries:

    http://developer.BlackBerry.com/Cascades/reference/bb__cascades__qlistdatamodel.html

    but I don't see how this could help. If the filtered data is changed, it must be merged with the original sort data.

    Why the original approach has not worked?

    I could not understand from the description appearance of the interface user, please post a screenshot if possible.

  • Created in the ListView lost when C++ ListItem custome context reference

    Hi all

    I have a listview that generates a list of the custome listviewItems (ie the containers). Containers have a setContextProperty to my database object. But when they are added to the list view, I can't access the database context property. I realize that the listview is not in the same context as the page but I don't understand why when I bind context for the real item the reference he lost?

    Error: asset:///WorkoutListItem.qml:17: ReferenceError: can't find variable: _Dal

    List.QML

    
    Page
    {
    Container { ListView { id: workoutList horizontalAlignment: HorizontalAlignment.Fill
    
     dataModel: _Dal.ListofWorkouts listItemComponents: [ ListItemComponent {  type: "item" WorkoutListItem { workoutId: ListItemData.id workoutName: ListItemData.name } } ] }//End List }//End root
    }//EndPage
     
    

    WorkoutListItem.qml

    
    Container { id:root property int workoutId: -1 property variant workoutName: ""
    
     layout: StackLayout { orientation: LayoutOrientation.LeftToRight }
    
     Button { id: workoutDelete text: "Delete" onClicked: { var result = _Dal.DeleteWorkout(root.workoutId) } }
    
     Label { id: workoutNumberLabel text: root.workoutId }
    
     Label { id: workoutNameLabel text: root.workoutName }
    
     Button { id: workoutEdit text: "Edit" onClicked: { //TODO: Open workout page } }}
     
    

    application.cpp

    
    QmlDocument *WorkoutListItem = QmlDocument::create("asset:///WorkoutListItem.qml").parent(this);
    WorkoutListItem->setContextProperty("_Dal", dal);
    

    Thanks in advance for any help

    -J

    itemRoot.ListItem.view.yourFunction(ListItemData)
    

    yourFunction (data) is defined in the ListView itself

    from there, you have access to your context

  • ListView: ListItemComponents (QML) vs ListItemProvider/Auditors (C++)

    Hello

    I develop an application that uses a list view, which contains different types of list items (one with a single image, with lots of text and 3 photos, etc...)

    I beguntaking the way of the implement in C++ because it did not seem possible based on QML so much I wanted to. I have my own DataModel inheriting from the ArrayDataModel class, and a form that inherits from ListViewItemFactory ListItemProvider and various ListItemListeners. These ListItemListeners all contain the equivalent of C++ code QML which create a container (containers, updates page, inages, labels, etc...)

    My question is, can I use my own datamodel and support QML for my ListView and his ListItemComponents instead of the ListItemProvider/ListItemListener equivalent in C++? If possible, why a person go about creating these in C++?

    Thank you

    Martin

    You can certainly do it in QML by substituting the itemType in javascript function in your ListView control. I think this is good for simple cases where you're not different, but several types of items when you have a lot of guys, and the code becomes more complex, it becomes a little heavy to do all the javascript. Especially if you are using custom data. Layer c ++ is also slightly more fast. You probably won't notice the difference, but there is a slight speed increase.

Maybe you are looking for

  • Satellite Pro L300 - PSLB9E - cannot turn off wifi except for by Win 7

    I installed Win7 64 bit with a custom installation (replacing 32-bit Vista). I have updated all drivers (to my knowledge) and BIOS to 2.1. The wifi is always enabled, any position of the switch on the front or the combination Fn + F8. I can unplug a

  • HP Officejet Pro 8600 Premium: Tray Lock worked until the upgrade of Windows 10

    Since a year now, I have 1 locked drawer for our book of receipt only, easier than all the other printing set to automatically select the default tray to tray 2 (Tray 1 is locked and all)! But I tried the upgrade of Windows 10, that was an epic fail

  • moving channels

    I'm new to LabView please be patient. I have a binary number represented as a string. I want to pass this 16-bit number and fill the main pieces of 0. I have to cut this string? I know that tables can be shifted to n number of times but couldn't find

  • Windows 7 - set up a backup - error code: 80070422

    Trying to make a backup for the first time on Windows 7 and get error code 80070422. A run "sfc /verifynow" to check the file system and had no reported problems. The following services are started: COM event system + / start / automatic DCOM Server

  • Windows 7 photo viewer will not display all images, except in slide show mode.

    I use a laptop computer with a monitor connected via a dock of the USC.  Everything worked fine until today.  When I use the monitor as the only display, windows 7 Photo Viewer does all the images except in slide show mode.   To be more precisely, af