[Interest] Syncing settings between QML and C++

Marc Van Daele marc.van.daele90 at gmail.com
Wed May 13 21:58:42 CEST 2020


Hello,

I try to read settings in C++ that are written from within QML.
But apparently, I need some delay between writing the value in QML and
reading the new value in C++ (even when calling settings.sync() in both QML
and C++).
Apparently, I have to wait about 1000ms (500ms sometimes works, sometimes
doesn't)

The following code illustrates the problem.
My QML code looks like this

import QtQuick 2.12

import QtQuick.Window 2.12

import Qt.labs.settings 1.0


Window {

    id: root

    visible: true

    width: 640

    height: 480

    title: qsTr("Hello World")


    property int ctr: 0


    Settings {

        id: settingsId

        property alias ctr: root.ctr

        onCtrChanged: {

            console.info("QML: before C++ call ctr = "+root.ctr + "//" + ctr)

            settingsId.sync();

            readSettings.printSettings("try ")

            Qt.callLater(tryAgain)

            tryAnotherTime.start()

            console.info("QML: after C++ call ctr = "+root.ctr)

        }


        function tryAgain() {

            settingsId.sync();

            readSettings.printSettings("try again ")

        }

    }


    Timer {

        id: tryAnotherTime

        interval: 1000

        onTriggered: readSettings.printSettings("try in timer ")

    }


    MouseArea {

        anchors.fill: parent

        onClicked: root.ctr++

    }

}


The relevant C++ printSettings() function is

void ReadSettings::printSettings(QString prefix)

{

    QSettings settings;

    settings.sync();

    int ctr = settings.value("ctr", "-1").toInt();

    qInfo() << "ReadSettings::printSettings "<< prefix << " read ctr=" << ctr;

}

The ReadSettings object is registered as a context property in main.pp

When I run this code, I get the following log lines

qml: QML: before C++ call ctr = 8//8
ReadSettings::printSettings  "try "  read ctr= 7
qml: QML: after C++ call ctr = 8
ReadSettings::printSettings  "try again "  read ctr= 7
ReadSettings::printSettings  "try in timer "  read ctr= 8

This shows that the first two calls to printSettings still print the old value.

The call after 1000ms prints the correct value


Is this a bug?  Do you see work-arounds I can try?


Kind Regards,


Marc
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20200513/3487a006/attachment.html>


More information about the Interest mailing list