QVariantMap passage of QML
I need to fill a QVariantMap with values, QML, and then pass to a C++ function, like this:
QVariantMap map; map["type"] = type; map["date"] = strDate; map["value"] = value; map["unit"] = unit; _app.addItem(map);
How to achieve this in QML? Is there a QVariantMap or equivalent type that will allow me to do in QML?
Thank you!
I expect the QML engine to convert a regular JavaScript 'object' of a QVariantMap when you switch to a C++ function. Just try with _app.addItem ({type: type, day: strDate, value: value, unit: Unit}) and see what he does.
Tags: BlackBerry Developers
Similar Questions
-
Passage of QML variable to the Web format
So I have a QML file as follows
Container { id: cont property variant numArray: ["1","2","3","4","5"] WebView { id: webView html: "" + "" + " onCreationCompleted: { console.log(numArray[0]) } } }
and the pie.js has the following
onload=function(){ document.write(numArray[0]) };
In the QML, WebView signal, "onCreationCompleted" file, print the correct value.
However, JS, numArray variable is not written in the page in the file.
My code is not exactly the same, but the structure is the same. How can I do for passing the QML variable in the file JS inside the WebView?
Thank you!
Using the method in this tutorial should work: http://www.bbcascades.com/index.php/tutorial-list/52-passing-information-to-html-from-qml
-
Another Question for C++ question QML class
Hello
I have a class that I joined in QML. I have a couple of Q_PROPERTY int and QString. Now I would like to spend a lot of information to the QML which includes data elements. I would spend the entire data group from the C++ QML and then have easy access to data elements.
I was wondering what the best structure to allow that load the structure in C++ and access the items in the QML.
Thanks in advance.
Just thought that I would finalize the solution that worked and marks it as such.
all
class PData::PData(QObject* parent) { Q_PROPERTY(QVariantList pData READ pData NOTIFY pDataChanged) public: QVariantList pData(); signals: void pDataChanged(); private: QVariantList m_pData;
.cpp
QVariantList PClass:pData() { return m_pData; } void function() { QVariantMap tMap; tMap["t1"] = 1; tMap["t2"] = 2; m_pData.append(tMap); emit pDataChanged();}
. QML
onPDataChanged: { var pItem = myPData.pData; var dataMap = pitem[0]; var t1 = dataMap["t1"]; var t2 = dataMap["t2"]; } attachedObjects: [ PData { id: myPData }]
Thanks to all who helped.
-
Hey,.
I have a declared list like so:
ListView { id: PostsList preferredWidth: 700 objectName: "PostsList" layoutProperties: DockLayoutProperties { horizontalAlignment: HorizontalAlignment.Center } // A single component because there's no list header. listItemComponents: [ ListItemComponent { type: "post" PostItem { } } ] //Tried this hoping items were being misparsed as headers. function itemType(data, indexPath) { return 'item'; } }
Where is PostItem.qml
Container { id: itemRoot layout: DockLayout { leftPadding: 30 rightPadding: leftPadding topPadding: 30 } Container { preferredHeight: 250 layout: DockLayout { } Label { //text: ListItemData.data.title text: ListItemData.title layoutProperties: DockLayoutProperties { verticalAlignment: VerticalAlignment.Center horizontalAlignment: HorizontalAlignment.Center } } Label { //text: ListItemData.data.title text: ListItemData.description layoutProperties: DockLayoutProperties { verticalAlignment: VerticalAlignment.Center horizontalAlignment: HorizontalAlignment.Center } } } // Signal handler for list item activation. ListItem.onActiveChanged: { setHighlight (ListItem.active); } // Signal handler for list item selection. ListItem.onSelectedChanged: { setHighlight (ListItem.selected); } }
If you begin to feel that this code resembles stamp collector, you something...
in any case, I stated as follows the data model for the list, copy the following code runs in a callback function SLOT QNetworkAccessManager...
QList
map;QVariantMap variant;foreach (post, posts) { variant.clear(); variant.insert("id", post->id); variant.insert("title", post->title); variant.insert("author", post->author); map.insert(map.length(), variant); } ListView *PostsList = mNav->findChild ("PostsList"); QListDataModel *model = new QListDataModel ; model->setParent(this); model->clear(); QVariantMap v; int i = 0; foreach(v, map) { model->insert(i,v); i++; } PostsList->setDataModel(model); Here is what I expected to happen.
I compile and debug the program. Some code I have send the network request. I analyze the JSON in a QList
(which is my own type). From their I looked in a QList (map, called in the code above). Once I put my ListView data model as the variable according to the guidelines of this line: PostsList-> setDataModel (model);
"PostsList" list updates in the application and displays the data from post-> title, as that inserted in the QVariant inserted in QVariantMap on this line:
Variant. Insert ("title", post-> title);
Instead, what is shown is the post-> data of the author, and the only reason I can possible design that is displayed (in reality the point post about 13 members, I removed most of length) is that it is the first in alphabetical order and seems to be the first member of the QVariantMap variable. The author of the message is the unique label presented, so declared both in the QML labels seem to be ignored.
When I select a list item (by using the code is essentially identical to the example of stampcollector) and page through the QDeclarativeContext method all members of the QVariantMap are accessible and can be used to display items QML.
Here is an example of how the stamp collector app that performs in the OnSelectionChanged handler:
ListView* PostsList = dynamic_cast
(sender()); DataModel* Model = PostsList->dataModel(); // Update the content view context property so that it corresponds to // the selected item and navigate to the page. QVariantMap map = Model->data(indexPath).toMap(); mQmlContext->setContextProperty("_contentView", map); mNav->push(mContentPage); Can someone explain the behavior that I receive? Why can't I access the articles through the ListItemData.member method as described in the documentation?
Note: some minor code changes have been made for length and clarity, the code has no compiler errors and like I said the DataModel code works at least to a certain extent all the data members that I expect to be accessible in ListItemData are available in _contentView.
I haven't checked in depth, but the first thing I would try, is to change your function to return 'post' instead of "item", since you have a component for "post". I will try an example.
Stuart
-
pass data from childCardDone to a textfield in QML?
I have a card camera call function that responds with the path of the image once a picture is registered using the childCardDone function. I have no idea how to pass data from c ++ to qml. I know that during the passage of the QML for C++ database, you set a QString & something. How can I do the reverse?
Here's my CPP code:
void App::childCardDone(const bb::system::CardDoneMessage &message) { if (message.reason() == "done") // Need the message.data() info in my QML message.data(); qDebug() << message.reason() << "\n"; qDebug() << message.dataType() << "\n"; qDebug() << message.data() << "\n"; } public slots: void childCardDone(const bb::system::CardDoneMessage &message);
and I just want to get the value of message.data () into a textfield label in QML:
Label{ id: capturedFilePath text: <
> } All help is appreciated and will be loved and accepted as a solution if it works.
Thanks in advance.
For use in your function you will need to decalre in the header.
In the header to declare,
AbstractPane * root;
Then, change
AbstractPane * root = qml->
() createRootObject; TO
root = qml-> createRootObject
(); -
Fill ListView C++ QML
Hello!
I created interface using QML. I have a ListView but I want add data by using c++.
I guess, the easiest is to send ListView pointer as an argument to the function c ++. I'm trying to do something like that.
QML
Page { Container { Label { // Localized text with the dynamic translation and locale updates support text: qsTr("Hello World") + Retranslate.onLocaleOrLanguageChanged textStyle.base: SystemDefaults.TextStyles.BigText } ListView { id: contacts_lw; } } onCreationCompleted: { app.fillListView(contacts_lw); } }
C++ Builder
qml->setContextProperty("app", this);
function
Q_INVOKABLE void ApplicationUI::fillListView(ListView & lw) { GroupDataModel *model = new GroupDataModel(QStringList() << "first_name" << "last_name"); JsonDataAccess jda; QVariantMap jsonmap = jda.load(QDir::currentPath() + "/app/native/assets/contacts.json").toMap(); QVariantList list = jsonmap["response"].toList(); model->insertList(list); lw->setDataModel(model); }
How to make it work?
use a pointer, not a reference as a parameter.
If ListView is unknown as a parameter, you can either use qmlRegisterObject to publicize or use a QObject * as a parameter and cast him. -
How to send data from c ++ to qml to an another qml.
Hello
I'm quite confused about a simple problem, I'm sure. Let me put some of my code and then I'll ask my question
hand. QML
// Default empty project template import bb.cascades 1.0 import bb.data 1.0 // creates one page with a label TabbedPane { Menu.definition: MenuDefinition { actions: [ ActionItem { title: "Refresh" } ] } showTabsOnActionBar: true Tab { title: qsTr("Employee") NavigationPane { id: everyonePane Page { id: everyoneFeed ListView { objectName: "FeedView" id: FeedView layout: StackListLayout { headerMode: ListHeaderMode.Sticky } listItemComponents: [ ListItemComponent { type: "item" DetailFeed { } } ] } } attachedObjects: [ ActivityIndicator { objectName: "indicator" verticalAlignment: VerticalAlignment.Center horizontalAlignment: HorizontalAlignment.Center preferredHeight: 200 preferredWidth: 200 } ] onCreationCompleted: { } } } Tab { title: qsTr("TimeSheet") Page { } } Tab { title: qsTr("Calendar") Page { } } }
detailView
import bb.cascades 1.0 Container { layout: StackLayout { orientation: LayoutOrientation.TopToBottom // this line stacks everything below } bottomPadding: 20 Container { // single row id: row1 // individual row container layout: DockLayout { } preferredWidth: maxWidth Container { // container for image preferredWidth: 150 //size of image if known preferredHeight: 150 topPadding: 10 leftPadding: 20 horizontalAlignment: HorizontalAlignment.Left verticalAlignment: VerticalAlignment.Center ImageView { preferredWidth: 150 //size of image if known preferredHeight: 150 imageSource: "asset:///images/person.jpg" // some image } } // stack labels Container { // container for labels horizontalAlignment: HorizontalAlignment.Left // align this container to the left translationX: 200 verticalAlignment: VerticalAlignment.Center layout: StackLayout { orientation: LayoutOrientation.TopToBottom // this stacks the labels } Label { objectName: "firstname" text: "first label" } Label { text: "second label" } } } Divider { } }
Employee.cpp
// Default empty project template #include "Employee.hpp" #include
#include #include #include #include #include #include #include using namespace bb::cascades; QString mQueryUri; Employee::Employee(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 mQml = QmlDocument::create("asset:///main.qml").parent(this); // create root object for the UI mRoot = mQml->createRootObject (); // Retrieving my activity indicator //mActivityIndicator = mRoot->findChild ("indicator"); //mActivityIndicator->start(); // Retrieving my list from QML mListView = mRoot->findChild ("dribbbleFeedView"); GetFeed("everyone"); // set created root object as a scene app->setScene(mRoot); } void Employee::GetFeed(QString feedType) { // First off we initialize our NetworkManager QNetworkAccessManager* netManager = new QNetworkAccessManager(); if (!netManager) { qDebug() << "Unable to create QNetworkAccessManager!"; emit complete("Unable to create QNetworkAccessManager!", false); return; } // First off we initialize our NetworkManager netManager = new QNetworkAccessManager(); if (!netManager) { qDebug() << "Unable to create QNetworkAccessManager!"; emit complete("Unable to create QNetworkAccessManager!", false); return; } mQueryUri = "http://mycompany" + feedType; // We setup our url QUrl url(mQueryUri); QNetworkRequest req(url); // Setup the reply and connect to the reply function QNetworkReply* ipReply = netManager->get(req); connect(ipReply, SIGNAL(finished()), this, SLOT(onReply())); } void Employee::onReply() { QNetworkReply* reply = qobject_cast (sender()); QString response; bool success = false; if (reply) { if (reply->error() == QNetworkReply::NoError) { int available = reply->bytesAvailable(); if (available > 0) { int bufSize = sizeof(char) * available + sizeof(char); QByteArray buffer(bufSize, 0); int read = reply->read(buffer.data(), available); response = QString(buffer); success = true; Q_UNUSED(read); } } else { response = QString("Error: ") + reply->errorString() + QString(" status:") + reply->attribute( QNetworkRequest::HttpStatusCodeAttribute).toString(); qDebug() << response; } reply->deleteLater(); } if (response.trimmed().isEmpty()) { response = "Request failed. Check internet connection"; qDebug() << response; } bb::cascades::GroupDataModel* dm = new bb::cascades::GroupDataModel( QStringList() << "id"); dm->setGrouping(bb::cascades::ItemGrouping::None); // parse the json response with JsonDataAccess bb::data::JsonDataAccess ja; QVariant jsonva = ja.loadFromBuffer(response); QVariantList feed = jsonva.toMap()["employee"].toList(); QVariantMap player; foreach (QVariant v, feed) { QVariantMap feedData = v.toMap(); dm->insert(feedData); } mListView->setDataModel(dm); mListView->setVisible(true); } OK so here is my question. I load a listview, in my hand, calling another qml, detailview. Given that my PPC is load my json file how can I send what I receive in my datamodel in my detailfeed can I change we tell the label with objectName: "firstname" to change the text for datamodel.name?
Hope I am clear enough.
Thank you
I think that you can access ListItemData in detailView.qml. Say ListItemData.id.
Why do you add only a mapping in groupdata. I think you need to add all the necessary fields such as firstname and so on. Right?
bb::cascades::GroupDataModel* dm = new bb::cascades::GroupDataModel( QStringList() << "id");
-
Access a list of QObjects using Javascript of QML?
I want to access a list of QObjects of Javascript so that they are accessible for example like this:
var items = mycontextproperty.getItems() for(i =0; i< items.length; i++){ items[i].name; }
I expect fair access properties read-only.
In C++, I have a what method defined like this
Q_INVOKABLE QList getItems()
or like this
Q_INVOKABLE QVariantList getItems()
and then I manually add QObject * to QVariantList
Neither one seems to work. Does anyone know how to expose a simple list in C++ QML?
I think that you can implement to get the stitch data of C++.
var size = mycontextproperty.getItemSize() for(i =0; i< size; i++){ //name = mycontextproperty.getItemName(i); var data = mycontextproperty.getItem(i); //Should have a try with QVariantMap }
-
Save QVariantMap in the memory for use in a LIstView
I want to make a simple application that has a ListView QML based on a simple C++ created simple QVariantMap. I want the user to be able to add and subtract items from the QVariantMap. I know how to do all that, but how do I save the changes to the QVariantMap they persist between sessions?
simplest is to persist QVariantMap use JsonDataAccess
something like this:
void KinveyJSONCache::writeCache(const QVariant& data) { JsonDataAccess jda; jda.save(data, yourPathToFile);
-
Method to apply a style HTTP in Cascades/QML?
Something like AJAX. What is the equivalent in Cascades/QML? What classes should I Explorer in the API?
Advice would be greatly appreciated.
Applications vary.
http://someservice.com/v1/do/blah
http://someservice.com/v1/do/meh
The output of the service is JSON.
I'll take the exit and probably put it in a list (much like the sample application of stamp collector)
Help me get started at all help or sample code would be really useful. I imagine that it would be useful for developers who integrate their stunts BB10 app API or data of third parties.
Thank you!
Hello
I wrote a simple example application to show how to create an application that consumes a twitter feed and display JSON content crawled in a standard list view.
First create a new project named 'Twitter', by selecting file-> New-> BlackBerry Cascades C++ Project, and then choose the option "Empty project" Standard.
We will start by creating a class called TwitterRequest responsible for the download and let us know through the slots and signals that the twitter JSON data is available. This class must be placed in your src/folder of the project
TwitterRequest.hpp
/* * Copyright (c) 2011-2012 Research In Motion Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TWITTERREQUEST_HPP_ #define TWITTERREQUEST_HPP_ #include
/* * This class is responsible for making a REST call to the twitter api * to retrieve the latest feed for a twitter screen name. It emits the complete() * signal when the request has completed. */ class TwitterRequest : public QObject { Q_OBJECT public: TwitterRequest(); virtual ~TwitterRequest(); /* * Makes a network call to retrieve the twitter feed for the specified screenname * @param screenname - the screen name of the feed to extract * @see onTimelineReply */ void getTimeline(QString screenname); public slots: /* * Callback handler for QNetworkReply finished() signal */ void onTimelineReply(); signals: /* * This signal is emitted when the twitter request is received * @param info - on success, this is the json reply from the request * on failure, it is an error string * @param success - true if twitter request succeed, false if not */ void complete(QString info, bool success); }; #endif /* TWITTERREQUEST_HPP_ */ TwitterRequest.cpp
/* * Copyright (c) 2011-2012 Research In Motion Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "TwitterRequest.hpp" #include
#include #include #include #include TwitterRequest::TwitterRequest() { } TwitterRequest::~TwitterRequest() { } void TwitterRequest::getTimeline(QString screenname) { QNetworkAccessManager* netManager = new QNetworkAccessManager(); if (!netManager) { qDebug() << "Unable to create QNetworkAccessManager!"; emit complete("Unable to create QNetworkAccessManager!", false); return; } QString queryUri = "http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_n..."; queryUri += screenname; QUrl url(queryUri); QNetworkRequest req(url); QNetworkReply* ipReply = netManager->get(req); connect(ipReply, SIGNAL(finished()), this, SLOT(onTimelineReply())); } void TwitterRequest::onTimelineReply() { QNetworkReply* reply = qobject_cast (sender()); QString response; bool success = false; if (reply) { if (reply->error() == QNetworkReply::NoError) { int available = reply->bytesAvailable(); if (available > 0) { int bufSize = sizeof(char) * available + sizeof(char); QByteArray buffer(bufSize, 0); int read = reply->read(buffer.data(), available); response = QString(buffer); success = true; } } else { response = QString("Error: ") + reply->errorString() + QString(" status:") + reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString(); qDebug() << response; } reply->deleteLater(); } if (response.trimmed().isEmpty()) { response = "Twitter request failed. Check internet connection"; qDebug() << response; } emit complete(response, success); } Then, replace the main.qml with the following content.
import bb.cascades 1.0 Page { content: Container { background : Color.DarkRed layout : DockLayout { } ListView { layoutProperties : DockLayoutProperties { verticalAlignment : VerticalAlignment.Center } objectName : "basicTimelineView" id : basicTimelineView listItemComponents: [ ListItemComponent { type: "item" StandardListItem { statusText: { ListItemData.created_at } descriptionText: { ListItemData.text } } } ] } } onCreationCompleted: { cs.getTimeline("ladygaga"); } }
This is a simple page with a ListView with standard components, indicating the date and the content of the tweet. As you can see, immediately after that page is created a call is made in the c++ code by using the context property 'cs' set in the constructor for the App to retrieve the latest tweets of the usernamed "ladygaga". To learn more about the call c ++ QML here https://bdsc.webapps.blackberry.com/cascades/documentation/ui/integrating_cpp_qml/index.html
Finally, this linking is the App class. It uses slot machines to handle the "full" signal generated by the class TwitterRequest when data are available, analyzes the data in a model of GroupData and fills the ListView with the recovered data.
App.HPP
#ifndef APP_H #define APP_H #include
#include class App : public QObject { Q_OBJECT public: App(); /* * Called by the QML to get a twitter feed for the screen nane */ Q_INVOKABLE void getTimeline(QString screenName); public slots: /* * Handles the complete signal from TwitterRequest when * the request is complete * @see TwitterRequest::complete() */ void onTwitterTimeline(QString info, bool success); protected: bb::cascades::AbstractPane* m_root; }; #endif // ifndef APP_H App.cpp
#include
#include #include #include #include #include "App.hpp" #include "TwitterRequest.hpp" using namespace bb::cascades; App::App() { QmlDocument *qml = QmlDocument::create("main.qml"); qml->setContextProperty("cs", this); m_root = qml->createRootNode (); Application::setScene(m_root); } void App::getTimeline(QString screenName) { //sanitize screenname QStringList list = screenName.split(QRegExp("\\s+"), QString::SkipEmptyParts); if (list.count() <= 0) { qDebug() << "please enter a valid screen name"; return; } QString twitterid = list[0]; TwitterRequest* tr = new TwitterRequest(); tr->getTimeline(twitterid); connect(tr, SIGNAL(complete(QString, bool)), this, SLOT(onTwitterTimeline(QString, bool))); } void App::onTwitterTimeline(QString info, bool success) { if (!success) { qDebug() << "Error retrieving twitter fee: " << info; return; } ListView* list = m_root->findChild ("basicTimelineView"); if (!list || list->dataModel() != NULL) { qDebug() << "basic list already populated"; return; //if basic timeline list not found or already populated do nothing } // Create a group data model with id as the sorting key GroupDataModel* dm = new GroupDataModel(QStringList() << "id_str"); dm->setGrouping(ItemGrouping::None); // parse the json response with JsonDataAccess bb::data::JsonDataAccess ja; QVariant jsonva = ja.loadFromBuffer(info); // the qvariant is an array of tweets which is extracted as a list QVariantList feed = jsonva.toList(); // for each object in the array, push the variantmap in its raw form // into the ListView for (QList ::iterator it = feed.begin(); it != feed.end(); it++) { QVariantMap tweet = it->toMap(); dm->insert(tweet); } // set the data model to display list->setDataModel(dm); list->setVisible(true); } I hope that's enough to help you get started. There are many improvements that can be made, for example using multiple pages, load the ajax style tweets, even having a page where the twitter user name can be changed, and so on of error handling. Good luck!
See you soon
Swann
-
Retreive QvaraintMap values of Custom QObject in QML
Hello
I'm working on an application that has a general usecase of getting data from the server and show it on the client.
Here is the code for a better understanding
//NetworkCommunicator.hpp class NetworkCommunicator: public QObject { Q_OBJECT Q_PROPERTY(QString url READ url WRITE setUrl) Q_PROPERTY(Weather weather READ weather WRITE setWeather) public: ................... void setWeather(Weather weather); Weather weather(); void setUrl(QString url); QString url(); signals: void dataAvailable(); void error(); private: QNetworkAccessManager *vNetworkAccessManager; Weather vWeather; QString urlStr; ........... // NetworkCommunicator.cpp ........................... vWeather.setLocationMap(rootMap.value("yweather:location").value
()); vWeather.setUnitsMap(rootMap.value("yweather:units").value ()); vWeather.setWindMap(rootMap.value("yweather:wind").value ()); //Weather.h ................. Q_PROPERTY(QVariantMap unitsMap READ getUnitsMap WRITE setUnitsMap); Q_PROPERTY(QVariantMap windMap READ getWindMap WRITE setWindMap); //QML NetworkCommunicator { id: networkCommunicator url: "http://weather.yahooapis.com/forecastrss?w=2442047&u=c" onDataAvailable: { console.log("got response " + networkCommunicator.url); console.log("weather " + networkCommunicator.weather); console.log("weather.unitsmap " + networkCommunicator.weather.getUnitsMap.value("distance")); activityIndicator.stop(); } } Here is the result
has got the answer http://weather.yahooapis.com/forecastrss?w=2442047&u=c
QVariant (Weather) weather
..................................... 3/native/Assets / / hand. QML:26: TypeError: result of expression 'networkCommunicator.weather.getUnitsMap' [undefined] is not an object.The issue could be included in the output.
Netcommunicator request a data server and analyzes the data and affects weather analyzed data object receives the response.
But after that I couldn't retrieve the string data to weather object that stores in the form of QvariantMap.
Any help is very appreciated.
As I could not achieve this is QML, I created the view in C++ and started using that. Thanks for you help guys.
-
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: eventsModelHere 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.
-
I have this QML who have a ListView with datasource to a full ArrayDataModel from the CPP file for creationcompleted, I loop in the table to add the hour together to appear as a label on the page, what works. However, when I want to view these items in the list, it will display only the first element of the QVariantMap within the table, no error on the log of the device. Also, triggered more does not work, but when I click it, it will have a blue border surrounding it, but the onTriggered does not fire.
Here is an excerpt of the CPP on the table fill
This-> eventsModel = new ArrayDataModel();
QVariantMap event;
event ['EventName'] = "Event1";
event ["EventHour"] = "00";
event ["EventMinute"] = "01";
event ["EventSecond"] = '02 ";
QML-> setContextProperty ("eventsModel", it-> eventsModel);
Here's the QML
{Of container
ID: eventListContainer
{To ListView
ID: eventList
dataModel: eventsModel
Use a ListItemComponent to customize the appearance of the list view
listItemComponents:]
{ListItemComponent}
type: 'point '.
{StandardListItem}
Title: 'Event' + ListItemData.EventName;
Description: "time:" + ListItemData.EventHour + ":" + ListItemData.EventMinute + ":" + ListItemData.EventSecond; "»
}
}
]
onTriggered: {}
var selectedEvent = dataModel.data (row);
var eventDetailPage = eventDetailDefinition.createObject ();
eventDetailPage.txtEventName.text = selectedEvent ['EventName'];
eventDetailPage.pickEventTime.value = picker.dateFromTime(selectedEvent["EventHour"]+":"+selectedEvent["EventMinute"]+":"+selectedEvent["EventSecond"]);
eventDetailPage.open ();
}
}
Any help would be appreciated.
Thank you.
ListView determines ItemType of the element by calling the function itemType of the dataModel. By default, an ArrayDataModel returns an empty string for this call (see https://developer.blackberry.com/cascades/reference/bb__cascades__arraydatamodel.html).
This leaves you with a few options:
(1) If you have no header and all the elements are the same, you can make
ListItemComponent { type: "" ...
(2) If you have headers or different elements, you can extend ArrayDataModel and implement your own function of itemType
(3) you can define a function of ItemType on your ListView in QML. Documentation:
ListView called DataModel::itemType() for each item in order to know the type. QML, this can be overridden by declaring the itemType function (data, row) on the ListView element. ListView then call this function instead of the function DataModel.
Here's how to create a list in QML which creates a header for all items on the high level and aStandardListItem for each item below the top level:
-
easy passage will not work with the new fire fox - it works with google. Why
passage not easy auto fill ID of user or password after the upgrade to the new version of F.F. It works very well on the google browser.
Also can I get easy to work in the new safe area browser?
OS = VistaYes easypass does not work with 22 for now go back to the previous version
-
In the Pages, after copying a passage, a box pops up that I can not remove
In the PAGES, after copying a passage, a box appears that I can't delete and I can't edit the passage
What Pages, what the passages, where?
If it's around the text and you copied this on the Internet, probably you just caught a few html formatting to the text. Paste without style.
Peter
Maybe you are looking for
-
I searched for weeks for a solution to this, but I have not been able to find one. The only way for me to hear anything when a call is if I choose my monitor like device speaker on Skype and the Jack of 3.5 mm on then plug it into my computer's line-
-
Toolbox icons are not displayed (are hidden) (not shown)
I install LV8.6 and overall the palette of tools for icons only. The tool palette do not show the icons of high level when the display is set to icons only. The icons are there, they are not displayed. Anyone know how to fix this? I have a PC here th
-
"ocxinstall" listed in Add/Remove programs
In my control panel in Add/Remove programs is a file/application/program title ocxinstall. I've never heard or seen this before. It is great 956 MB and after clicking on the support link I am informed that the editor is "apexis' version 1.0.0.32.
-
Error service there is no 0 x 80070424 on Vista 64-bit for the installation of SP2
Hello I use a 64-bit version of Vista SP1. I am trying to install SP2, but in the end, it does not work. I have an error message that Setup could not install and this message: error service there is no 0 x 80070424. I also installed the file: Windows
-
HP Photosmart Premium C310 prints at all. No error message about ink.
suggest measures to remedy the situation