incorporating a qml conditional statement when assigning a class

I have an item and I want to dynamically add a class based on a variable

import "class1"
import "class2"

Item { 
    id: myID
    property variant myVar: 0;
    
    anchors.fill: parent;
    
    function update() { 
        switch(myID.myVar) {
            case 0:        
                class1 {
                    anchors.fill: parent;
                }       
                break;
                
            case 1:
                class2 {
                    anchors.fill: parent;
                }
                break;
        }
    }

}

It seems like there may be an issue with the current code, is there a correct way to achieve this?

Thank you.

Answer №1

When working with QML and JavaScript, it's important to remember that QML class instantiation syntax does not work in a JavaScript context. Once a QML file is loaded, all class instances within it are already instantiated.

To dynamically create components, you need to define two components and use a loader. The code snippet below should point you in the right direction, although it hasn't been tested yet.

import "class1"
import "class2"

Item {
  id: myItem
  property variant myVar: 0;
  anchors.fill: parent;

  Component { 
    id: compClass1
    class1 {
      anchors.fill: myItem;
    }
  }       
  Component { 
    id: compClass12    
    class2 {
      anchors.fill: myItem;
    }
  } 
  Loader { id: myLoader }      

  function update() { 
    switch(myID.myVar) {
    case 0:
      myLoader.sourceComponent = compClass1;
      break;
    }
    case 1:
      myLoader.sourceComponent = compClass2;
      break;
    }
  }
}

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

Custom JavaScript function throwing an error

function changeElementClass(path, changeClass, duration){ $(path).removeClass(changeClass); $(this).addClass(changeClass); )}; $('.flightDetails .option').changeElementClass('.flightDetails .option','selected',300); ...

transferring data from JavaScript to PHP variables

Currently, I am working on a project that involves using ajax to access the database asynchronously. The value retrieved is stored in a JavaScript variable like this: var content=xmlhttp.responseText; My next step is to pass this value to the PHP module ...

Tips for turning off hash-based redirection in AngularJS

Here is a specific URL: http://www.something.com/sometest/test/#registration Some code has been written based on #registration for Internet Explorer. However, when using AngularJS, it redirects to the following URL, which disrupts the logic: http://www ...

The chai property "matchSnapshot" is not valid

https://i.sstatic.net/4wgqq.png After following the instructions provided at this link, I am now in the process of writing basic Jest tests for my React application that uses the Create-React-App starter kit. I came across a recommendation mentioned here ...

What is the most effective method for embedding a Kotlin program into a website?

I have created a combat simulation tool in Kotlin for an online gaming community. Users can input the combat levels of two players, choose the number of duels to simulate, and then initiate the simulation which will provide win percentages and other stats. ...

Steps for deactivating the submit button once confirming the presence of the username and email

When using AJAX to verify the existence of an email or username in the database, I want to deactivate the submit button if either one (or both) already exist. Currently, I have successfully changed the input border color but I am facing a challenge with t ...

Is it a cookie-cutter function?

Can someone help me solve this problem: Implement the special function without relying on JavaScript's bind method, so that: var add = function(a, b) { return a + b; } var addTo = add.magic(2); var say = function(something) { return something; } ...

Problem with JQUERY Galleria CSS positioning alignment specifically in Firefox, Chrome works without issues

I recently incorporated jquery Galleria into my website and I am currently facing an alignment issue with the div element gallery-container. Interestingly, it appears correctly aligned in Chrome but is shifted to the right in Firefox. You can view the webs ...

Add a class to alternate elements when mapping over data in React

Check out the code snippet below: <div className="grid md:grid-cols-2 sm:grid-cols-2 grid-cols-1 gap-16 mt-24 px-4"> {status === "success" && delve(data, "restaurants") && data.r ...

Guide on how to return a JSON result as a Dictionary instead of an Array using Express.js

I need to format my response as a dictionary with specific key-value pairs, like so: { "id": 5928101, "category": "animal welfare", "organizer": "Adam", "title": "Cat Cabaret& ...

What is the best way to incorporate multiple variables in a MySQL query when using Node.js?

I'm facing a challenge where I need to input student data into a table using the parent key as a foreign key. The parent information is included in the same JSON object, with an array of students inside it. My goal is to retrieve the parent Id from th ...

Recording a specialized event sent from a web component to React

Trying to incorporate a Lit web component into a React application has presented some challenges for me. This web component is expected to dispatch a custom event at some point, and I need to handle it in the React application appropriately. Despite my li ...

How to interrupt a JQuery animation and restart it from the middle?

Currently, I am tackling my first JQuery project and facing a challenge. As the user mouseleaves the .container, the animation does not reset but continues as if they are still within it. My goal is to have the animation revert in reverse if the user decid ...

Generate an additional element for each element when clicked, triggering an error warning

When creating a form, I want to display an error message next to each invalid element when the submit button is clicked. Although I am close, the issue is that it adds the span tag twice after the element if two elements are invalid. I need it to be added ...

Is there a way to switch out the ionic2-super-tabs Toolbar for the ion-slides pager feature?

Hello there, Currently, I am utilizing the following plugin in my Ionic 3 project: https://github.com/zyra/ionic2-super-tabs The plugin offers a great functionality for swipeable tabs in Ionic applications. In its documentation, it demonstrates how to hi ...

Is there a way in Reactjs Material UI 5 (MUI5) to unselect only the star that was clicked, without affecting the rest of the stars in the

For instance: I selected the 3rd star on the rating component, but when I click on it again, all the previous stars disappear and it shows 0 stars. How can I make it so that if I click on the 3rd star a second time, only the 3rd star is removed, leaving ...

What steps can be taken to resolve the issue of "Access Denied: Invalid token, incorrect code"?

Assigned to me recently for a school project is a coding challenge that consists of various parts. The final task involves uploading to a private GitHub repository and submitting a completion request through a POST request under specific conditions. I hav ...

Encountering a Component Exception error in React Native while attempting to implement a Victory chart component

Currently, I am exploring the Victory library for react native to create a line chart for my budgeting application. Below is the code snippet from my Graph component: import React from 'react'; import { View, StyleSheet } from 'react-native& ...

Unable to Click on Selenium Element

When a link is clicked on a website, the URL remains unchanged but a popup appears on the screen containing elements that can only be accessed after running driver.switchTo().defaultContent(). To access these elements, I have used a javascript executor com ...

Tips for handling numerous observables in Angular 7

I am working on an Angular 7 application that deals with a total of 20 sensor data. My goal is to receive data from a selected sensor every 5 seconds using observables. For example: var sensorId = ""; // dynamically chosen from the web interface var senso ...