Using QML to pass a JavaScript object to a C++ member function

I am attempting to send a JS object (map) to a C++ member function with the following signature

Q_INVOKABLE virtual bool generate(QObject* context);

using

a.generate({foo: "bar"});

The method is being called (confirmed via breakpoint), however, the passed context parameter is appearing as NULL. The documentation states that JS objects will be sent as QVariantMap, so I tried using this signature:

Q_INVOKABLE virtual bool generate(QVariantMap* context);

This resulted in an error during MOC compilation. Next, I attempted:

Q_INVOKABLE virtual bool generate(QVariantMap& context);

but at runtime, QML was unable to find the method (error message indicated "Unknown method parameter type: QVariantMap&").

The documentation only provides an example of sending a QVariantMap from C++ to QML, not vice versa.

Switching to a public slot instead of Q_INVOKABLE yielded the same results and errors.

Answer №1

It is recommended not to use references to pass values from the QML world to CPP world. The following example demonstrates a simple and effective approach:

test.h

#ifndef TEST_H
#define TEST_H

#include <QObject>
#include <QDebug>
#include <QVariantMap>

class Test : public QObject
{
    Q_OBJECT
public:
    Test(){}

    Q_INVOKABLE bool generate(QVariantMap context)
    {qDebug() << context;}
};

#endif // TEST_H

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "test.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    engine.rootContext()->setContextProperty(QStringLiteral("Test"), new Test());

    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

main.qml

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    MouseArea
    {
        anchors.fill: parent
        onClicked:
        {
            Test.generate({foo: "bar"});
        }
    }
}

When you click in the window, the following message will be printed in the output console:

QMap(("foo", QVariant(QString, "bar")))

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

Utilizing jQuery to delete items once their corresponding checkboxes are checked

I have successfully implemented a feature where I can add more fields by clicking a button. However, I am facing an issue when trying to delete a field after checking the checkbox. Any assistance on this matter would be greatly appreciated. jQuery: $(doc ...

Tips for integrating error management in Angular with RXJS

Implementing error handling in the use case method by using subscriptions is my goal. When an error occurs in the adapter, the handling should be done in the use case. However, in the code snippet provided below, the catch block does not seem to work pro ...

Angular version 7.2.1 encounters an ES6 class ReferenceError when attempting to access 'X' before it has been initialized

I have encountered an issue with my TypeScript class: export class Vehicule extends TrackableEntity { vehiculeId: number; constructor() { super(); return super.proxify(this); } } The target for my TypeScript in tsconfig.json is set to es6: ...

webpack is encountering difficulty resolving the node_modules material-icons directory

Encountering an Error ERROR in ./node_modules/material-icons/iconfont/material-icons.css (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[5].use[2]!./node_mod ...

Efficiently sanitizing a JavaScript object using the replace() method in JavaScript

I have a data object structured like this {"paymethod_id":1,"business_id":76,"delivery_type":"1","driver_tip":0,"delivery_zone_id":6569,"delivery_datetime":null,"location":{&qu ...

Issue encountered during creation of a polyline in Cesium

When attempting to create a polyline in my ReactJs app using the code below, I encountered an error message stating "DeveloperError: Expected value to be greater than or equal to 0.0125, the actual value was 0." Can someone shed some light on why this er ...

A method for displaying both the next and previous steps without relying on a switch case statement

I have an array list as follows: const data = [ { title: 'Title1', }, { title: 'Title2', }, { title: 'Title3', }, { title: 'Title4', ...

Node.js not resetting array properly

I have successfully set up a Node+Express API that is working smoothly, but I am facing an issue with returning responses for complex queries. The problem lies in the fact that the variable where I store the response data is not being reset between differe ...

The reflow feature in Highcharts does not properly update the width of the container for High

https://i.sstatic.net/8Shix.gif I am currently working on adjusting the width of Highcharts dynamically to fit its parent container. To achieve this, I have set up a mechanism that listens to changes in the sidebar state and triggers a reflow function whe ...

Explain the concepts of URL decoding and URL encoding

Currently collaborating on a web API project with my team, and came across the following code snippet: params.forEach(function (item, index) { params[index] = decodeURI(item); }); Can someone explain what purpose this function serves? ...

What is the best way to transfer a multidimensional array from PHP to JavaScript?

Attempting to extract array value from a JSON string, I utilize the json_decode function in PHP. <?php $jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php'); $jsonDecoded=json_decode($jsonContent,true); foreach($jsonEncoded[&apo ...

The form does not display the radio button value upon submission

Using redux form for the form elements, I encountered an issue where the radio button values were not being displayed when submitting the form. Despite getting values for email and password fields, the role value from the radio buttons was missing. In my i ...

Deactivating Button Features in Wx Widgets

Currently, I am utilizing the WxDev framework to design the graphical user interface for our software. Within the interface, there are two essential buttons: "Upload" and "Analyze". The desired sequence of actions involves the user uploading an image, fol ...

What is the solution to resolving the error "null property 'role' cannot be read"?

I'm encountering an issue whenever I enter the following code: if(message.member.roles.cache.has(`something here`)) An error is displayed stating "Cannot read property 'role' of null" Does anyone have any solutions or suggestions to resol ...

What is the process for specifying a dependency on an ng-metadata module?

I am currently working on a project that is utilizing ng-metadata for creating a few Angular 1.5 modules. One of the test modules/components in this project has the following structure: import { NgModule, Component, Inject, Input, Output, EventEmitter } f ...

The application unexpectedly minimizes when the "Show Desktop" or "Minimize All" button is clicked

In my extensive application which utilizes multiple threads and a graphical user interface, I have noticed an issue with the minimize functionality. When clicking the minimize button in the title bar, the application closes promptly. However, if I use the ...

Switching minimum and maximum input values based on a specific condition: A step-by-step guide

I am looking for a way to reverse the minimum and maximum values of two input elements that I have defined. Is there a way to achieve this using HTML or JavaScript (Angular)? Here is an example of what I am trying to do: <label> Width: < ...

Guide to utilizing jQuery for setting values in all subsequent rows of a table

I have a table with 15 rows of text boxes labeled as text1, text2, and so on up to text15. If I enter text into, let's say, the 5th textbox, I want that same text to be automatically copied into all subsequent textboxes from the 6th through the 15th. ...

What could be causing the issue of only the title being visible and not the content in Next.js when using next-mdx-remote?

I am having an issue with rendering MDX content on a page using next-mdx-remote with Next.js. Currently, only the title from the frontmatter is being displayed, while the actual MDX content is not showing up. Below is the code snippet showcasing my setup: ...

Organize intricate JavaScript Arrays

Similar Question: How to sort an array of javascript objects? I'm in the process of transitioning some of my older ActionScript 2.0 code to JavaScript. While most things are running smoothly, I've hit a roadblock when trying to numerically s ...