Exploring the retrieval of JavaScript array elements from a ListModel within QML

Currently, I have some JavaScript data that consists of a list of objects containing other objects and arrays, which I want to append to a ListModel.

This is what the structure looks like (assuming that the data is generated elsewhere and its structure should be avoided):

import QtQuick 2.0

Rectangle {
  width: 600
  height: 300

  ListView {
    anchors.fill: parent

    model: ListModel {
      id: listModel
    }

    delegate: Text {
      text: 'key: '+ key + ', subdict["subkey1"]: ' + subdict.subkey1 +
            ', sublist.count: '+ sublist.count + ', sublist[0]: '+ sublist[0] +
            ', sublist.get(0): '+ sublist.get(0)
      wrapMode: Text.WordWrap
      width: parent.width
      color: index % 2 == 0 ? "darkgreen" : "brown"
   }

   Component.onCompleted: {
    var values = [
                   {'key': 'foo1', 'subdict': {'subkey1': 'subfoo1', 'subkey2': 'subbar1'},
                    'sublist': ['subvalue1', 'subvalue2']},
                   {'key': 'foo2', 'subdict': {'subkey1': 'subfoo2', 'subkey2': 'subbar2'},
                    'sublist': ['subvalue3', 'subvalue4', 'subvalue5']},
                   {'key': 'foo3', 'subdict': {'subkey1': 'subfoo3', 'subkey2': 'subbar4'},
                    'sublist': []}
                 ]

    for (var i in values)
      listModel.append(values[i]);
   }
  }
}

Although most parts work fine, I am having trouble accessing the elements within sublist. I can only retrieve the count of items since they are actually a new ListModel. It seems impossible to retrieve the actual content using something like sublist.get(0).

Could this be a bug, or am I overlooking something?

Answer №1

This response originates from Jairo's feedback and offers a valuable workaround for cases where the model is read-only and dynamic updates are not required.

The solution involves setting the javascript object as the listview model and accessing elements in the delegate using the modelData keyword.

import QtQuick 2.0

Rectangle {
  width: 600
  height: 300

  ListView {
    anchors.fill: parent

    delegate: Text {
      text: 'key: '+ modelData.key + ', subdict["subkey1"]: ' + modelData.subdict.subkey1 +
            ', sublist.length: '+ modelData.sublist.length + ', sublist[0]: '+ modelData.sublist[0] +
            ', sublist: ['+ modelData.sublist + ']'
      wrapMode: Text.WordWrap
      width: parent.width
      color: index % 2 == 0 ? "darkgreen" : "brown"
   }

   Component.onCompleted: {
    model = [
              {'key': 'foo1', 'subdict': {'subkey1': 'subfoo1', 'subkey2': 'subbar1'},
              'sublist': ['subvalue1', 'subvalue2']},
              {'key': 'foo2', 'subdict': {'subkey1': 'subfoo2', 'subkey2': 'subbar2'},
              'sublist': ['subvalue3', 'subvalue4', 'subvalue5']},
              {'key': 'foo3', 'subdict': {'subkey1': 'subfoo3', 'subkey2': 'subbar4'},
              'sublist': []}
            ]
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Slider-activated Pie Chart Controller

I have successfully created a pie chart using highchart and javascript, allowing me to adjust each slice individually using a slider. However, I am facing an issue where I want the maximum value of the pie to be 100%, with the other sliders contributing to ...

Header formatting issue when attempting to implement tablesorter plugin

I implemented the widget-scroller and widget column Selector in my table using the table sorter plugin in jQuery. Has anyone encountered a problem like the one shown in this picture? It seems that my table headers do not align with the columns properly an ...

Unable to upload any further verification documents to Stripe Connect bank account in order to activate payouts

Query - Which specific parameters should I use to generate the correct token for updating my Stripe bank account in order to activate payouts? I've attempted to activate payouts for my Stripe bank account by using a test routing and account number (t ...

What are the steps to implement Vuelidate 2 in a web browser?

Back in the stone age, we used to just drop in a .js file or a CDN reference and start coding. But now things seem much more complicated. I'm trying to use Vuelidate 2 in the browser, but I can't seem to figure it out. I've already done npm ...

Arranging elements in an array based on two different properties

Trying to organize an array of elements (orders details). https://i.stack.imgur.com/T2DQe.png [{"id":"myid","base":{"brands":["KI", "SA"],"country":"BG","status":&qu ...

Is it possible to create a sticky element that stays fixed to the window without using JavaScript?

Using position: sticky has been a game-changer for me. It resolves many issues without the need for JavaScript. However, I've encountered a roadblock. I am trying to create a sticky element that is nested inside multiple <div> elements. Since po ...

Get Onsen UI 2 up and running without the need for Angular

Is it possible to install Onsen UI 2 without Angular? I have tried following various guides from , but when attempting the JavaScript method (> npm install onsenui) I consistently encounter a ReferenceError: angular is not defined. How can I properly in ...

Fetching data using an Ajax request in PHP is encountering issues, whereas the same request is successfully

I am experiencing an issue with a simple Ajax call in ASP.NET that works fine, but encounters a strange DOM Exception when I insert a breakpoint inside the onreadystatechange function. Can anyone explain why ASP.NET seems to have some additional header log ...

What are the best practices for managing promises effectively?

Currently, in my Angular application, I am utilizing $odataresource for handling data retrieval and updates. The code snippet I am working with is as follows: var measure = $odataresource("http://windows-10:8888/ChangeMeasure/"); var myMeasure = measure ...

Inserting HTML content into a DIV with the help of jQuery

Looking for a solution with my index.html file. I want to load other HTML files into a DIV by clicking on buttons. Here's an example of what I'm trying to achieve: I've searched through various examples online, but none seem to work for ...

React Native: Picker value remains static

I'm encountering an issue where the value of the picker does not change when I select a new value from it. This problem started occurring after I added the onValueChange function. If anyone has any insights or suggestions on how to resolve this, I wou ...

Creating diverse content for various tabs using JavaScript

I have developed a code that uses a for loop to generate tabs based on user input. var tabs = ""; var y = 1; for (var x = 0; x < tabNum; x++) { tabs += "<li class = 'tabbers'>" + "<a href='#tab'>Tab</a>" + "& ...

What is the method of duplicating an array using the array.push() function while ensuring no duplicate key values are

In the process of developing a food cart feature, I encountered an issue with my Array type cart and object products. Whenever I add a new product with a different value for a similar key, it ends up overwriting the existing values for all products in the ...

A guide to reordering table rows by drag-and-drop with JavaScript

Seeking assistance with swapping table rows using JQuery UI. Although successful in the swap, struggling to retrieve row numbers during the drag and drop event. Understanding the row number is essential for subsequent tasks. Any help would be greatly appre ...

Sharing a session with a Django template using jQuery

I am attempting to use $.load() to load a Django template that contains {% if user.is_authenticated %}. However, when the template is rendered on the server in response to an AJAX-generated HTTP request, the user object is undefined. Here is my_template.h ...

React DnD now enables dragging an entire list of cards instead of just a single card

Implementing react DnD in my react Project has been challenging. In the render method, I have defined a variable called Populate that generates a list of cards as shown below: render() { var isDragging = this.props.isDragging; var connect ...

Utilizing jQuery to convert object properties into a table

Here is the table structure I am working with: <table> <thead> <tr> <th>Loan Type</th> <th>Amount Borrowed</th> <th>Current Payment< ...

JavaScript code for initiating the npm start command

Is it possible to include the npm-start command in a JavaScript script? Requirement: Develop a JS script capable of triggering the npm-start command. Operating System: Microsoft Windows I need to turn it into a Windows service. However, in the code snip ...

The Google Docs viewer is displaying an empty screen

I have been utilizing the Google Docs viewer on my website: <div class="embed-r embed-responsive-a"> <iframe class="embed-responsive-it" src="https://docs.google.com/viewer?embedded=true&amp;url=http://LINK.PDF"></iframe> </div& ...

Discover the position of the element that was clicked within the group of elements sharing the

Here is my HTML code: <input type="button" class="buttonclose marleft fleft clrPric" value="X"> <input type="button" class="buttonclose marleft fleft clrPric" value="X"> <input type="button" class="buttonclose marleft fleft clrPric" value= ...