Filling ListView disorder

Hello

I have a problem inserting a QVariantList data in a ListView by using a GroupDataModel. The application works, but the list is empty. I confirmed that the QVariantList is not empty. I have been struggling with this for a while and you'd be grateful for any help.

Since the constructor of the app:

mDb = new databaseHandler();

mQml = QmlDocument::create("asset:///main.qml");
-setContextProperty expose QML as a C++ object variable
{If (! mQml-> {hasErrors())}
-> setContextProperty mQml ("app", this);
mTimer = new QTimer (this);
Connect (mTimer, SIGNAL (timeout ()), this, SLOT (update ()));

mRoot = mQml-> createRootObject();
loadData();
Application::instance()-> setScene (mRoot);

int i = 9;
}
on the other
{
QList error = mQml-> errors();
}

Sub App::loadData()
{
QString databaseName = "timetracker_test_data.db";
mTimeEntries = mDb-> loadDataBase (databaseName);
GroupDataModel * mDataModel = mRoot->findChild ("timeEntryModel");

QVariantList sqlData.

for (int count = 0; count)< mtimeentries.count();="" count="">
{
QVariantMap timeEntryMap;
timeEntryMap ['description'] is mTimeEntries [count] .getDescription ();.
int time = mTimeEntries [count] .getTotalTime ();

timeEntryMap ['time' = intTimeToString (time);
sqlData.append (timeEntryMap);
mRoot-> setProperty ("currTimeText", mTimeEntries [count] .getDescription ());
mDataModel-> insert (timeEntryMap);

}

mDataModel-> insertList (sqlData);
}

From main.qml:

{To ListView
ID: listContainer
itemTextStyle variant of property: defaultBlackTextStyle
dataModel: timeEntryModel

listItemComponents:]
{ListItemComponent}
type: 'TimeEntry.
{TimeEntry}
}
}
]
attachedObjects:]
A GroupDataModel is used for the presentation of the SQL data. The installation is made here
with the exception of the actual population of the model, which is done in C++.
{GroupDataModel}
ID: timeEntryModel
objectName: "timeEntryModel."
}
]
}

and TimeEntry.qml:

{Of container
layout: {StackLayout}

}
{Label
The title is related to the data of the models title attribute / recipemodel.xml.
text: ListItemData.description;
textStyle {}
Base: SystemDefaults.TextStyles.TitleText
color: Color.Black
}
}
{Label
The title is related to the data of the models title attribute / recipemodel.xml.
text: ListItemData.time;
rightMargin: 25.0
leftMargin: 25.0
layoutProperties: {StackLayoutProperties}

}
rotationZ: 0.0
textStyle {}
Base: SystemDefaults.TextStyles.TitleText
color: Color.Black
}
}
}

Thanks for the replies on this one. Turns out I was diagnose the issue wrong all along. It turns out that my listview has been filled from the beginning, but a UI issue was causing my listview can be hidden by another component. (don't ask why I never checked this first) The nice thing about this 'non-issue', it is that I now know how the listview works both inside and outside that I tried all possible methods to solve this problem

Gerry

Tags: BlackBerry Developers

Similar Questions

  • Unable to fill ListView with vector

    I'm using a sample I got on the internet to create a listfield

    that contains an image and the data contained in a vector.

    Data are obtained from a JSON array that is created from a script php accessing a mysql database.

    The problem is that the listfield poster not only any content, even if there are items in the table.

    This is the code I use to get the JSON array data :

    JSONArray items_array=job.getJSONArray("items");
                        for(int i=0;i
    

    The code for the ListFieldCallback:

    class MyListModel implements ListFieldCallback
           {
    
               private ListField _view;
               private int _defaultRowHeight=32;
               private int _defaultRowWidth=_defaultRowHeight;
               private int _txtImagePadding=5;
               private Bitmap _bitmap;
                private Vector _data;
               public MyListModel(ListField list,Vector data)
                     {
                         _view=new ListField();
                        _data=new Vector();
                         _data=MyScreen.data_vec;
                         _view=list;
                         list.setCallback(this);
                        // _view.setSize(_data.size());
                         _view.setRowHeight(_defaultRowHeight);
                         _bitmap=null;
    
                         //list.setSize(_data.size());                     
    
                         }
    
               public void drawListRow(ListField list,Graphics g,int index,int y,int w)
               {
                   Items itemToDraw=(Items)this.get(list,index);
                   String name=itemToDraw.getName();
                   g.drawText(name,_defaultRowWidth+_txtImagePadding,y,DrawStyle.LEADING|DrawStyle.ELLIPSIS,w-_defaultRowWidth-_txtImagePadding);
    
                   g.drawBitmap(0,y,_bitmap.getWidth(),_bitmap.getHeight(),_bitmap,0,0);
    
                   }
    

    The code for the method of success which must now fill listview:

    public void success(final Vector listboys)
            { 
    
              UiApplication.getApplication().invokeLater(new Runnable()
              {public void run()
              {
                 data_vec=new Vector();
              data_vec=listboys;
              Items it1=(Items)data_vec.elementAt(0);
              error("Vector Main Screen " +it1.getName());
                                 final MyListField myListView=new MyListField();
          final  MyListModel myListModel=new MyListModel(myListView,data_vec);
         myListView.addToContextMenu(myListModel.getAddMenuItem(0,0));
        myListView.addToContextMenu(myListModel.getRemoveMenuItem(0,0));
        myListView.addToContextMenu(myListModel.getModifyMenuItem(0,0));
        myListView.addToContextMenu(myListModel.getEraseMenuItem(0,0));
    
        {
            Manager vfm=getMainManager();
            vfm.add(myListView);
            vfm.add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
            setTitle("List Demo Title");
    
            }
    

    The listview is always empty. I don't see where data is passed to display. Whenever I call:

    list.setSize(_data.size());
    

    I always get a null pointer exception. How can I get the listview to display the data contained in the vector itemsholder. Thank you

    using images in a listfield is not difficult, to improve that worked for you.

    You can use drawBitmap to draw the image in the listfield.

  • Fill ListView using the C++ model

    Hello

    Sorry to bother, I guess my question must be pretty basic, but I'm new to bb10 SDK,

    What I intend to do is to show in a listview items, I calculated in C++. (In C++, because the logic for calculating them was quite complex)

    There, in the QT doc, you have exactly what I dream of:

    https://Qt-project.org/doc/Qt-5.1/QtQuick/QtQuick-modelviewsdata-cppmodels.html

    Unfortunately, I have several questions:

    -ownership model, seems to exist. But I guess we use dataModel in our context, right?

    -J' I also need to get the declarative context of the QmlDocument which I think is correct.

    -the delegate property also doesn't seem to exist, but I understand that I must use instead ListItemComponents ( http://developer.blackberry.com/native/reference/cascades/bb__cascades__listitemcomponent.html)

    But I'm still confused on how I should provide the data for the list view.

    Now, when I expose my QList of DataObject, as described in the Doc of QT and which gives as data to the dataModel is told that he cannot "affect QDeclarativeListReference to bb::cascades:ataModel."

    So I guess I have to use a QListDataModel instead of use a Qlist <>, or?

    Well, any help in pointing me to the right documentation would be very appreciated!

    Thank you

    fill us our data model in c ++ as well.

    For this, we use a Q_INVOKABLE method that gets the listview as a parameter.

    The ListView itself is created in QML.

    ListView* listView = dynamic_cast(listViewParameter);
    GroupDataModel* model = dynamic_cast(listView->dataModel()); if (model) {        model->clear();    } else {        model = new GroupDataModel(QStringList() << "sortParameter");        model->setGrouping(ItemGrouping::ByFullValue);        listView->setDataModel(model);    }//calculate stuffmodel->insertList(stuff);
    
  • 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.

  • Way idiomatic for the item displayed in the ListView

    I have a ListView with a StackListLayout and SnapMode.LeadingEdge. ListItemComponent fill ListView together, so there is only one display item at a time (except animations).

    What is the idiomatic way to get the row of the displayed item?

    Recent firstVisibleItem property SDK version appears in ListScrollStateHandler. I didn't want to use it again. There is also firstVisibleItemChanged signal:

    https://developer.BlackBerry.com/Cascades/reference/bb__cascades__listscrollstatehandler.html#firstv...

    What I currently use for similar task is engaging LayoutUpdateHandlers to all items in the list and follow their updates to determine which element is the most visible. But the elements to stop sending updates when you go off the screen. I also had to use a timer to stop monitoring of off-field elements. If the first approach does not work I can give more details on this one.

  • indicator problem ListView and activity

    Hi, I was playing around with the sample application address book so that I have included a button to re-populate the list view. It takes a few seconds, that's why I've included an indicator of activity runs while the list view is being filled.

    The activity indicator is supposed to start when the button is pressed and stop when the display of the list has been entered.

    Now, my problem is that the activity indicator seems to start when the display of the list has been populated (it just starts and stops in a Flash). I have also included a header which changes the onbuttonclicked text to check if that was the problem-indicator of activity but same thing happening (text only changes after listview is filled). The list view appears to stop all operations until it was settled.

    What is the cause and how can I solve this problem? Thank you.

    onButtonClicked {}
    change the header text
    start the activity indicator
    fill listview
    }

    Then in c ++ after m_model-> insert (map) I emit a stop to the activity indicator signal.

    Indicator text and header activity does not change until the listview has been briefed.

    as the list of all the opinions of the population occurs on the event thread indicator gets no time to do things.
    If you would like to fill in the asynchronous list, it should work as expected.

    as a sidenote: have a look to refresh the headers, they are often used to reload a list.

  • Get the thumbnail of the file for ListView

    Is there a way to get the thumbnail of an image? I have a listview showing the list of selected images and I want to display the thumbnail and the name of the file. Here's what I have so far

    I let the user select a picture through the file picker that returns only the path of file then I go this path in a method to add it to the datamodel.

    CPP file: I spend in the path of the image file that has been selected

                QVariantMap itemMap;
            QFileInfo fileInfo = QFileInfo(filePath);
            itemMap["name"] = QVariant(fileInfo.fileName());
            itemMap["image"] = QVariant(fileInfo.filePath());
    
            if (indexOf(itemMap) == -1)
            {
                   insert(0, itemMap);
             }
    

    ListItem QML

    StandardListItem
    {
        id:pictureItem
        title: ListItemData.name
        imageSpaceReserved: true
        imagesource: ListItemData.image
    
    }
    

    I'm pretty new to this so I have a feeling strong on this issue, I'm going the wrong way, but I noticed that I get an error message saying: he can't access element of . My thought was that the image space would diminish the image to fit the placeholder

    For the error do you put the permission to access_shared?

    I suggest that you should be creating thumbnails of images, save them in the folder of application data and update the image of ListItem.

    If you experience a delay when filling ListView, then you must think of preloading images and caching.

  • Error "Index out of range" on search query

    I have a configuration of search query to clear my listview and insert new results of the query in the listview. The code looks like this:

    {OnDataLoaded}

    _APP. Clearlist

    root. ListView.insertlist (Data)

    }

    {OnQueryChanged}

    Load();

    }

    But unfortunately, whenever I do a query, and as a result appears my query update (triggered from a contextual menu) does not work and gives me the error "Index out of range". Even if the results of the query to fill listview very well and when I tap on a result it shows all data fine as well.

    And FYI the update query does not work when the list is not be searched or filtered so I don't think that there is a problem with my function.

    What I am doing wrong?

    He solved.  The problem is that the update function trying to remove and add the updated item within the filtered datamodel causing problems.  I just got the datamodel to load before performing the functions as described below:

    bool App::updateObject(const QString &id, const QString &name, const QString &description, const QString &datefield, const QString &lat, const QString &lon, const QString &categoryfield, const QString &mapurl, const QString &itempic)
    {
        bool updated = false;
        bool saved = false;
    
    //    if (!validateID(id))
    //        return false;
    
        Location *location = new Location(id, name, description, datefield, lat, lon, categoryfield, mapurl, itempic);
    
        // Find location in the datamodel.
        // Only the id is used by find(). This is because location
        // defines equality (==) as having the same id. (See the definition of "=="
        // in the location class.)
        const QVariantList updateIndexPath = m_dataModel->find(location);
    
        // update the item if found
        if (updateIndexPath.isEmpty()) {
            alert(tr("Object ID not found."));
            updated = false;
        } else {
            load();
            updated = m_dataModel->updateItem(updateIndexPath, location);
        }
    
        // Save the datamodel if we updated something.
        if (updated) {
            m_storage->deleteFromDB(id);
            saved = m_storage->save(m_lastCustomerID, m_dataModel);
            load();
            refreshGroup();
    
        }
    
        return (updated && saved);
    }
    
  • Groupdata model header text

    import bb.cascades 1.0
    
    Container {
    
        Container {
    
            preferredWidth: Infinity
            TopBrowse {
                layoutProperties: StackLayoutProperties {
                    spaceQuota: -1
                }
            }
            layoutProperties: StackLayoutProperties {
                spaceQuota: -1
            }
        }
        Container {
            layout: DockLayout {
    
            }
            horizontalAlignment: HorizontalAlignment.Center
            verticalAlignment: VerticalAlignment.Fill
            ActivityIndicator {
                id: activityIndicatorBrowse
                objectName: "activityIndicatorBrowse"
                horizontalAlignment: HorizontalAlignment.Center
                verticalAlignment: VerticalAlignment.Center
                running: true
            }
        }
        Container {
            verticalAlignment: VerticalAlignment.Fill
            ListView {
                objectName: "customListBrowse"
                id: customListBrowse
                dataModel: GroupDataModel {
                    id: theModel
                    sortingKeys: ["accounts", "accounts2"]
                }
                layout: StackListLayout {
                    headerMode: ListHeaderMode.Sticky
                }
                listItemComponents: [
                    ListItemComponent {
                        type: "header"
    
                        Header {
                            title: ListItemData.TITLE
    
                        }
                    },
                    ListItemComponent {
                        type: "item"
                        Container {
                            id: itemRootBss
    
                            background: ListItem.selected ? Color.Transparent : Color.Transparent
                            Container {
                                leftPadding: 30
                                topPadding: 10
                                rightPadding: 10
                                bottomPadding: 10
    
                                layout: StackLayout {
                                    orientation: LayoutOrientation.LeftToRight
                                }
                                Container {
                                    layout: StackLayout {
                                        orientation: LayoutOrientation.TopToBottom
                                    }
                                    layoutProperties: StackLayoutProperties {
                                        spaceQuota: 1
                                    }
                                    Label {
                                        text: ListItemData.TITLE
                                        textStyle.base: SystemDefaults.TextStyles.TitleText
                                        textStyle.color: Color.create("#52c1b1")
                                    }
                                    Label {
                                        text: ListItemData.AUTHOR
                                        textStyle.base: SystemDefaults.TextStyles.SubtitleText
                                        textStyle.color:  Color.create("#7bc92d")
                                    }
                                }
                                Container {
                                    verticalAlignment: VerticalAlignment.Center
                                    horizontalAlignment: HorizontalAlignment.Right
                                    layout: StackLayout {
                                        orientation: LayoutOrientation.LeftToRight
                                    }
                                    ImageView {
                                        imageSource: "asset:///images/ic_right_arrow.png"
                                    }
                                }
                            }
                            Container {
                                background: Color.create("#ffE0E0E0")
                                preferredHeight: 1
                                Divider {
                                    maxHeight: 1
                                    minHeight: 1
    
                                }
                            }
                        }
    
                    }
    
                ]
                onTriggered: {
    
                }
            }
    
        }
    
    }
    

    I nthg prinited title of the header. If I use listitemdata, I don't have the first letter.

    in this case, you can call a function of your ListView.

    If this is your component header named headerRoot

    ListItemComponent {
        type: "header"
        CustomListItem {
            id: headerRoot
            dividerVisible: true
            highlightAppearance: HighlightAppearance.None
            TrackedListHeaderContainer {
            }
        }
    }
    

    then inside the component you canreference a function of your ListView in this way:

    headerRoot.ListItem.view.dayOfWeek(ListItemData)
    

    Your ListView

    onTriggered: {
        //
    }
    function dayOfWeek(headerData) {
        return app.weekdayLocalized(headerData)
    }
    

    hope that gives you some ideas

  • [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".

  • ListView filling does not

    Hi all

    ListView in my app is not filling, here is the code snippet

    ListView {
                        id:sectionlistview
                        objectName: "sectionlistview"
    
                        ///dataModel: groupDataModel
                        listItemComponents: [
                            ListItemComponent {
                                id:row
                                type: "item"
                                CustomListItem {
                                    dividerVisible: true
                                    highlightAppearance: HighlightAppearance.Default
                                    Container{
                                        opacity: 0.9
                                        background: Color.create("#c0c0c0")
                                        layout: StackLayout {
                                         orientation: LayoutOrientation.TopToBottom
                                        }
                                        Label {
                                            text: ListItemData.name
                                            textStyle.base: myStyle.style
                                            textStyle.color: Color.create("#ffffff")
                                        }
                                    }
                                }
    
                            }
                        ]
                    }
    
    void ApplicationUI::fetchData(){
            listView = root->findChild("sectionlistview");
            model = new GroupDataModel(QStringList() << "name");
            model->clear();
            model->setGrouping(ItemGrouping::None);
            model->insert(dataName);
            listView->setDataModel(model);
    }
    

    dataName is a QVariantMap variable. The data are available in the variable, I checked that.

    The following, almost identical to yours works for me. There are a few things in your code, which I don't see, so it is difficult to check every detail. First, create a new application and replace applicationui.cpp, applicationui.hpp and main.qml with my code and then test it. If it works, check if your code against mine. If not, let me know the device and the version of the OS that you are testing.

    #ifndef ApplicationUI_HPP_
    #define ApplicationUI_HPP_
    
    #include 
    
    namespace bb
    {
        namespace cascades
        {
            class Application;
            class LocaleHandler;
        }
    }
    
    class QTranslator;
    
    /*!
     * @brief Application object
     *
     *
     */
    
    class ApplicationUI : public QObject
    {
        Q_OBJECT
    public:
        ApplicationUI(bb::cascades::Application *app);
        virtual ~ApplicationUI() { }
        Q_INVOKABLE void fetchData();
    
    private slots:
        void onSystemLanguageChanged();
    private:
        QTranslator* m_pTranslator;
        bb::cascades::LocaleHandler* m_pLocaleHandler;
    
    };
    
    #endif /* ApplicationUI_HPP_ */
    

    applicationui. HPP

    #include "applicationui.hpp"
    
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    using namespace bb::cascades;
    
    static AbstractPane *root = 0;
    
    ApplicationUI::ApplicationUI(bb::cascades::Application *app) :
            QObject(app)
    {
        // prepare the localization
        m_pTranslator = new QTranslator(this);
        m_pLocaleHandler = new LocaleHandler(this);
    
        bool res = QObject::connect(m_pLocaleHandler, SIGNAL(systemLanguageChanged()), this, SLOT(onSystemLanguageChanged()));
        // This is only available in Debug builds
        Q_ASSERT(res);
        // Since the variable is not used in the app, this is added to avoid a
        // compiler warning
        Q_UNUSED(res);
    
        // initial load
        onSystemLanguageChanged();
    
        // Create scene document from main.qml asset, the parent is set
        // to ensure the document gets destroyed properly at shut down.
        QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
    
        // Create root object for the UI
        root = qml->createRootObject();
    
        // Set created root object as the application scene
        app->setScene(root);
    
        qml->setContextProperty("app", this);
    
    }
    
    void ApplicationUI::onSystemLanguageChanged()
    {
        QCoreApplication::instance()->removeTranslator(m_pTranslator);
        // Initiate, load and install the application translation files.
        QString locale_string = QLocale().name();
        QString file_name = QString("SupportListView_%1").arg(locale_string);
        if (m_pTranslator->load(file_name, "app/native/qm")) {
            QCoreApplication::instance()->installTranslator(m_pTranslator);
        }
    }
    
    void ApplicationUI::fetchData()
    {
    
        QVariantMap dataName;
        dataName["name"] = "Martin";
        ListView* listView = root->findChild((const QString) "sectionlistview");
        GroupDataModel* model = new GroupDataModel(QStringList() << "name");
        model->clear();
        model->setGrouping(ItemGrouping::None);
        model->insert(dataName);
        listView->setDataModel(model);
    }
    

    applicationui.cpp

    import bb.cascades 1.2
    
    Page {
        Container {
            //Todo: fill me with QML
            Label {
                // Localized text with the dynamic translation and locale updates support
                text: qsTr("Hello World") + Retranslate.onLocaleOrLanguageChanged
                textStyle.base: SystemDefaults.TextStyles.BigText
            }
            Button {
                text: "Fetch Data"
                onClicked: {
                    app.fetchData();
                }
            }
            ListView {
                id: sectionlistview
                objectName: "sectionlistview"
    
                ///dataModel: groupDataModel
                listItemComponents: [
                    ListItemComponent {
                        id: row
                        type: "item"
                        CustomListItem {
                            dividerVisible: true
                            highlightAppearance: HighlightAppearance.Default
                            Container {
                                opacity: 0.9
                                background: Color.create("#c0c0c0")
                                layout: StackLayout {
                                    orientation: LayoutOrientation.TopToBottom
                                }
                                Label {
                                    text: ListItemData.name
                                    textStyle.base: myStyle.style
                                    textStyle.color: Color.create("#ffffff")
                                }
                            }
                        }
    
                    }
                ]
            }
        }
    }
    

    hand. QML

    Good luck!

    Martin

  • ListView control to fill the available screen height

    Hello

    Anyone know how I can set the height of a ListView in QML to use all of the available screen height? I tried to use:

    verticalAlignment: VerticalAlignment.Fill
    

    .. but who did not work.  ListView is a container which resides in a Page that is in a NavigationPane.  I tried to add the above property to all these elements, but it always gets cut to three-quarters of the height of the screen.

    Thank you.

    I just thought of it.  I had an ActivityIndicator below the ListView that took place.  I put the ActivityIndicator false visibility when I use it, and that fixed the problem.

  • Complete ArrayDataModel QML and filling data in ListView

    Hello

    the filepicker, I get the file + the path to a file. Now I extracted the path and the name of the file to the string «selectedFile»

    Now, I want to add these two channels to an ArrayDataModel, which displays the data in a listview, the file name as the title and filepath as description.

    Here is my code:

    // Main.qml
    
    ListView {
      id: listview
    
      dataModel: ArrayDataModel {
        id: theDataModel
      }
    
      listItemComponents: [
        ListItemComponent {
    
          StandardListItem {
    
             title: ListItemData   <------------------ here I want to display the filename
             description: "filepath"   <-------------- and here I want to display the filepath
             imageSource: "asset:///images/icon.png"
    
    [...]
    
    onFileSelected: {  selectedFile = selectedFiles[0];  [...]    var filepath = *a string*    var filename = *a string*    theDataModel.append([filename, filepath]); <-------------- how can I add the two strings correctly to the datamodel?}
    

    What my code for the time when I take a file is that it adds two items to the list the first file name as title the second filepath as a title.

    How to manage to give the file name-path to the datamodel so that I can read both of them and put them in the view list?

    // Main.qml
    
    ListView {
      id: listview
    
      dataModel: ArrayDataModel {
        id: theDataModel
      }
    
      listItemComponents: [
        ListItemComponent {
    
          StandardListItem {
    
             title: ListItemData.name       <---------------------------------------------------|
             description: ListItemData.path  <-----------------------------------------------|
             imageSource: "asset:///images/icon.png"                                              |
                                                                                                                            |
    [...]                                                                                                                  |
                                                                                                                            |
    onFileSelected: {                                                                                             |
      selectedFile = selectedFiles[0];                                                                     |
      [...]                                                                                                                |
        var filepath = *a string*                                                                              |
        var filename = *a string*                                                                            |
        theDataModel.append([filename, filepath]); <----------- how do I add the strings correctly so that I can us them in the list
    }
    

    Hello!

    For the arrayDataModel, I suggest you use this

    data var = {}
    'name': name of file,.
    'path': filepath
    }

    theDataModel.append (data);

    If you still have a problem, let me know!

    Simon

  • A simple example of filling the data from Json to a ListView.

    I want a simple example to inflate a listview with Json data.

    Examples of the sample do not work

    as we have a code example

    App.cpp

    App::App()
    {
        Page *root = new Page;
        ListView *listView = new ListView;
    
        // Create the data model, specifying sorting keys of "firstName" and "lastName"
        GroupDataModel *model = new GroupDataModel(QStringList() << "firstName"
                                                   << "lastName");
    
        // Create a JsonDataAccess object and load the .json file. The QDir::currentPath()
        // function returns the current working directory for the app.
        JsonDataAccess jda;
        QVariant list = jda.load(QDir::currentPath() +
                                 "/app/native/assets/employees.json");
    
        // Insert the data into the data model. Because the root of the .json file is an
        // array, a QVariant(QVariantList) is returned from load(). You can provide a
        // QVariantList to a data model directly by using insertList().
        model->insertList(list.value());
    
        qDebug()<<"the size of model is "<size()<<"\n";
    
        // Set the data model for the list view
        listView->setDataModel(model);
    
        // Set the content of the page and display it
        root->setContent(listView);    Application::setScene(root);
    }
    

    with the file employees.json of assets

    [
        {
            "firstName" : "Mike",
            "lastName" : "Chepesky"
            "employeeNumber" : 01840192
        },
        {
            "firstName" : "Westlee",
            "lastName" : "Barichak"
            "employeeNumber" : 47901927
        },
        {
            "firstName" : "Jamie",
            "lastName" : "Lambier"
            "employeeNumber" : 51239657
        },
        {
            "firstName" : "Denise",
            "lastName" : "Marshall"
            "employeeNumber" : 41239520
        },
        {
            "firstName" : "Matthew",
            "lastName" : "Taylor"
            "employeeNumber" : 01963597
        },
        {
            "firstName" : "Mark",
            "lastName" : "Tiegs"
            "employeeNumber" : 65321951
        },
        {
            "firstName" : "Karla",
            "lastName" : "Tetzel"
            "employeeNumber" : 03266987
        },
        {
            "firstName" : "Ian",
            "lastName" : "Dundas"
            "employeeNumber" : 29472012
        },
        {
            "firstName" : "Marco",
            "lastName" : "Cacciacarro"
            "employeeNumber" : 56446691
        }
    ]
    

    On the run, it shows a white screen with no list control.

    Thank you all for your answers, actually problem was not in the code. The problem is in the employees.json file I downloaded from developer site.

     

    [
        {
            "firstName" : "Mike",
            "lastName" : "Chepesky"      // after this ',' is missing
            "employeeNumber" : 01840192
        },
        {
            "firstName" : "Westlee",
            "lastName" : "Barichak"      // after this ',' is missing
            "employeeNumber" : 47901927
        },
        {
            "firstName" : "Jamie",
            "lastName" : "Lambier"    // after this ',' is missing
            "employeeNumber" : 51239657
        },
    
    ....................so on]
    

    means the error occurred when parsing json. Error very stupid . I have checked it sooner.

    So who uses this example json file in their applications. Please correct first, and then use.

     

  • ListView.leadingVisual ignores horizontalAlignment

    It seems that the ListView.leadingVisual simply ignores the horizontalAlignment property.

    I try using horizontalAlignment: HorizontalAlignment.Fill but it will be not just extend:

    leadingVisual: container}

    horizontalAlignment: HorizontalAlignment.Fill

    }

    Even if ListView is expanded, the only solution is to put the preferedWidth. No idea if it is wanted ot a bug?

    It seems to work when you set the layoutProperties + spaceQuota.

    layoutProperties: {StackLayoutProperties}

    spaceQuota: 1

    }

    Looks like the container around the leadingVisual has a StackLayout

    Still not sure if this should be considered a bug or not

Maybe you are looking for

  • Thunderbird 38.3 won't open Inbox

    Updated Thunderbird to 38.3 38.2. Thunderbird 38.3 does not open Inbox for accounts that have been in Thunderbird 38.2. Uninstalled Thunderbird 38.3 and re-downloaded and reinstalled from the Web of Thunderbird site. Recreated email accounts (imap of

  • Touchpad has completely stopped working

    Hey, my touchpad completely stopped working. I tried to download the driver and restart and the stuff, but nothing seems to work. There was formerly an icon for it down to the right on the toolbar, but that's even more here, it's like the software so

  • Impossible to rename or delete the file VI

    It drives me crazy. I'm working on a project. Save it. Completely close LV2012. Try to move the project to another location in Windows Explorer. But he always tells me now that there will be one of the file (s) is open in another program. I know for

  • I HAVE TO CANCEL MY ACCOUNT

    PLEASE HELP ME TO DELETE MY HOTMAIL ACCOUNT! I COMPLETELY CANCELED MY XBOX LIVE FOR MY EMAIL. AND IT WILL NOT LET ME CANCEL MY ACCOUNT... Help, please. Thank you

  • Wireless disconnects itself and Card Miniport Tun Microsoft shows error code 10. Help, please

    the wireless adapter turns off while being connected and if the connection is lost and even if the wireless router is placed rite nxt him he cnt detect it and then the computer must be restarted.