Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-127322

JSON.stringify() on property of type QVariantList reads property for every list element

    XMLWordPrintable

Details

    • All

    Description

      When a C++ classed exposed to QML has a property of type QVariantList and this property is serialized in QML via JSON.stringify() the property is read over again for each element in the list. This can be a serious performance issue and worked properly in Qt 6.2 and earlier. The expected behaviour is that the property is only read/evaluated once and the output of the provided example is just 1 instead of numbers 1…1001. As a workaround the type of the property can be changed to QJsonArray.

      Minimal working example:

      main.cpp

      #include <QCoreApplication>
      #include <QQmlContext>
      #include <QQmlEngine>
      #include <QQmlExpression>
      
      #include "Test.h"
      
      int main(int argc, char *argv[])
      {
      	QCoreApplication app(argc, argv);
      	QQmlEngine engine;
      	Test test;
      	engine.rootContext()->setContextProperty(QStringLiteral("test"), &test);
      	QQmlExpression(engine.rootContext(), nullptr, QStringLiteral("JSON.stringify(test.foo)")).evaluate();
      	return 0;
      }
      

      Test.h

      #pragma once
      
      #include <QQmlEngine>
      
      class Test : public QObject
      {
      	Q_OBJECT
      	QML_ELEMENT
      	Q_PROPERTY(QVariantList foo READ foo)
      public:
      	QVariantList foo() const
      	{
      		static int callCount = 0;
      		qCritical() << ++callCount;
      
      		QVariantList list;
      		for (int i = 0; i < 1000; i++)
      		{
      			list.append(i);
      		}
      
      		return list;
      	}
      };
      

      CMakeLists.txt

      cmake_minimum_required(VERSION 3.16)
      
      project(test VERSION 0.1 LANGUAGES CXX)
      
      find_package(Qt6 REQUIRED COMPONENTS Qml)
      
      set(CMAKE_AUTOMOC TRUE)
      
      qt_add_executable(test main.cpp Test.h)
      target_link_libraries(test PRIVATE Qt6::Qml)
      

      Attachments

        Issue Links

          No reviews matched the request. Check your Options in the drop-down menu of this sections header.

          Activity

            People

              qtqmlteam Qt Qml Team User
              tobydox Tobias Junghans
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

              Dates

                Created:
                Updated:

                Gerrit Reviews

                  There are no open Gerrit changes