<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[communicating from c++ to qml]]></title><description><![CDATA[<p dir="auto">Hi all<br />
I am new to qt qml i have tried communicating from qml to c++ by  exposing a class using context or by qml registering .Now i have placed a button and i am able to communicate to the c++ .But i am unable to do the reverse that is communicating from c++ to qml.<br />
For example i am firing a QTimer in c++ say on every trigger  a variable is incremented i want to display the same in qml how to proceed .Can anyone guide me with a simple example.Thank you</p>
]]></description><link>https://forum.qt.io/topic/70363/communicating-from-c-to-qml</link><generator>RSS for Node</generator><lastBuildDate>Tue, 07 Apr 2026 16:10:19 GMT</lastBuildDate><atom:link href="https://forum.qt.io/topic/70363.rss" rel="self" type="application/rss+xml"/><pubDate>Thu, 18 Aug 2016 17:41:29 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to communicating from c++ to qml on Sat, 20 Aug 2016 18:50:14 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/shiv">@<bdi>Shiv</bdi></a> You're welcome. Do tell if you get stuck down the road. :)</p>
]]></description><link>https://forum.qt.io/post/343332</link><guid isPermaLink="true">https://forum.qt.io/post/343332</guid><dc:creator><![CDATA[Red Baron]]></dc:creator><pubDate>Sat, 20 Aug 2016 18:50:14 GMT</pubDate></item><item><title><![CDATA[Reply to communicating from c++ to qml on Sat, 20 Aug 2016 13:52:07 GMT]]></title><description><![CDATA[<p dir="auto">HI <a class="plugin-mentions-user plugin-mentions-a" href="/user/red-baron">@<bdi>Red-Baron</bdi></a></p>
<p dir="auto">Thank you for the detailed explanation and example I will try to implement and let you know .</p>
<p dir="auto">Thanks</p>
]]></description><link>https://forum.qt.io/post/343319</link><guid isPermaLink="true">https://forum.qt.io/post/343319</guid><dc:creator><![CDATA[Shiv]]></dc:creator><pubDate>Sat, 20 Aug 2016 13:52:07 GMT</pubDate></item><item><title><![CDATA[Reply to communicating from c++ to qml on Sat, 20 Aug 2016 18:55:08 GMT]]></title><description><![CDATA[<p dir="auto">You have two ways of doing that:</p>
<ul>
<li>Get the QML item in your C++ code and change its properties/invoke its methods</li>
<li>Connect a C++ signal/slot to QML slot/signal</li>
</ul>
<hr />
<p dir="auto"><strong>Using properties and invoking methods</strong></p>
<p dir="auto"><code>QQuickView</code>, <code>QQuickWidget</code> etc. offer the <code>rootObject()</code> method, which returns the <code>QQuickItem</code> that is the top-level item of your QML code. There are a couple of things you have to keep in mind:</p>
<ol>
<li>
<p dir="auto">All involved have to have an <code>objectName</code> (not to be confused with <code>id</code> in QML, which is a totally different thing (very confusing omho)) including your widget (see 2 for C++ code):</p>
<pre><code>Rectangle {
  id: button // Used for accessing the item from QML
  objectName: "button" // Used for accessing the item from C++
}
</code></pre>
</li>
<li>
<p dir="auto">You need to add the widget as a <code>contextProperty</code> to the QML<br />
<strong>Example:</strong></p>
<pre><code>MyQQuickWidget::MyQQuickWidget(const QUrl &amp;source, QWidget *parent) : QQuickWidget(parent) {
    // Add the widget to the root QML context as a context property
    this-&gt;setObjectName("quickwidget"); // quickwidget will be used to reference your widget within your QML code
    this-&gt;rootContext()-&gt;setContextProperty(this-&gt;objectName(), this);
    this-&gt;setSource(source);
    ...
}
</code></pre>
</li>
</ol>
<p dir="auto">After doing that you can simply retrieve the respective items in your C++ code. For example</p>
<pre><code>QQuickItem* button = this-&gt;rootObject()-&gt;findChild&lt;QQuickItem*&gt;("button");
</code></pre>
<p dir="auto">will retrieve the <code>Rectangle</code> I've used in 1. as an example. You should of course always check if the returned value is <code>== Q_NULLPTR</code> to avoid access violation if the child cannot be found and you try to use it anyway.</p>
<p dir="auto">After successfully retrieving your QML item you can access its properties or even invoke it's method. For example</p>
<pre><code>button-&gt;property("width").value&lt;int&gt;()
</code></pre>
<p dir="auto">returns the <code>width</code> of your item. In order to avoid a situation where you access a property that doesn't exists I strongly recommend to check the validity of the property like so</p>
<pre><code>int width = 0;
if(button-&gt;property("width").isValid()) {
  width = button-&gt;property("width").value&lt;int&gt;();
  // Do something with width
  // For example increase it twice the length
   button-&gt;setProperty("width", width*2);
}
</code></pre>
<p dir="auto">I just wrote a <code>ListView</code> with a <code>ListModel</code> where I'm controlling a lot of their aspects in my C++ code. <code>ListModel</code> for example has the <code>move(int from, int to, int items)</code> method. You can use <code>QMetaObject::invokeMethod(...)</code> to trigger some sort of a method that is part of the QML object. I'm quite new to QML so I don't know all the methods that are out there for <code>Rectangle</code> and whatnot but in the case of <code>ListModel</code> I did</p>
<pre><code>QObject* listModel = this-&gt;rootObject()-&gt;findChild&lt;QObject*&gt;("listModel"); // listModel is the objectName of my ListModel used by a ListView
// Check if listModel retrieved correctly
// Optional: check if "move" is a method available for the retrieved QObject - a little bit more complex then with checking if a property exists
// ...

int from = 0; // Or whatever
int to = 10; // Or whatever
int items = 1; // Move a single item

// Use the listModel object to trigger its move(int from, int to, int items) method
QMetaObject::invokeMethod(listModel, "move",
                          Q_ARG(int, from),
                          Q_ARG(int, to),
                          Q_ARG(int, items));
</code></pre>
<p dir="auto">Using <code>Q_PROPERTY</code> is also something that is used widely. If you want to expose C++ data to QML context you need to make that data a <code>property</code> of your C++ object etc. (you still have to add your C++ object to the QML context using its object name though).</p>
<hr />
<p dir="auto"><strong>Using slots and signals</strong></p>
<p dir="auto">I find the great difference between how slots and signals are declared in C++ and QML very annoying but since its a huge part of how Qt works one might also use this technique. ;)</p>
<p dir="auto">Here's an example how to:</p>
<ul>
<li>Trigger a C++ slot using QML signal</li>
<li>Trigger a QML slot using a C++ signal</li>
</ul>
<p dir="auto"><strong>main.qml</strong> (stored inside <code>QRC</code> file with the alias <code>main</code>)</p>
<pre><code>import QtQuick 2.0

Rectangle {
    id: test
    width:  200
    height: 50
    x: 10
    y: 10
    signal handleText(string msg)

    Text {
        id: textItem
        objectName: "textItem"
        anchors.centerIn: test
        text: "Text set in QML"

        Connections {
            target: commObject
            onChangeText: {
                textItem.text = newText;
            }
        }
    }

    MouseArea {
        hoverEnabled: false
        anchors.fill: parent
        onClicked: {
            test.handleText(textItem.text)
        }
    }
}
</code></pre>
<p dir="auto"><strong>main.cpp</strong></p>
<pre><code>#include &lt;QtGui/QGuiApplication&gt;
#include &lt;QtQuick/QQuickItem&gt;
#include &lt;QtQuick/QQuickView&gt;
#include &lt;QQmlContext&gt;
#include &lt;QTimer&gt;
#include "CommObject.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    // Create instance of object with slots and signals
    CommObject co;
    co.setObjectName("commObject");

    // Create view
    QQuickView view;
    // Add reference to object to view's rootContext as property
    view.rootContext()-&gt;setContextProperty("commObject", &amp;co);
    // Load QML in view
    view.setSource(QUrl("qrc:/main"));

    // Retrieve top-level object which is a Rectangle
    QObject *rect = dynamic_cast&lt;QObject*&gt;(view.rootObject());
    // Connect QML signal to C++ slot
    QObject::connect(rect, SIGNAL(handleText(QString)),
                     &amp;co, SLOT(slotRetrieveText(QString)));

    view.show();

    // Now lets trigger the emission of the C++ signal to the QML slot using a timer
    QTimer timer;
    timer.setInterval(5000);
    co.setText("Text changed from C++");
    QObject::connect(&amp;timer, SIGNAL(timeout()), &amp;co, SLOT(slotTriggerChangeText()));
    timer.start();

    return app.exec();
}
</code></pre>
<p dir="auto"><strong>CommObject.h</strong></p>
<pre><code>#ifndef COMMOBJECT_H
#define COMMOBJECT_H

#include &lt;QObject&gt;

class CommObject : public QObject
{
    Q_OBJECT
public:
    explicit CommObject(QObject *parent = Q_NULLPTR);
    void setText(const QString &amp;msg);

signals:
    void changeText(const QString&amp; newText);

public slots:
    void slotTriggerChangeText();
    void slotRetrieveText(const QString &amp;msg);

private:
    QString text;
};

#endif // COMMOBJECT_H
</code></pre>
<p dir="auto"><strong>CommObject.cpp</strong></p>
<pre><code>#include "CommObject.h"
#include &lt;QDebug&gt;

CommObject::CommObject(QObject *parent) :
    QObject(parent),
    text("")
{
}

void CommObject::setText(const QString &amp;msg)
{
    this-&gt;text = msg;
}

void CommObject::slotTriggerChangeText()
{
    qDebug() &lt;&lt; "Triggering change text signal";
    emit changeText(this-&gt;text);
}

void CommObject::slotRetrieveText(const QString &amp;msg)
{
    qDebug() &lt;&lt; "Received text from QML: \"" &lt;&lt; msg &lt;&lt; "\"";
}
</code></pre>
<p dir="auto">Declaring <code>signal handleText(string msg)</code> (in QML) actually does two things - it creates a signal and a slot with the slot being automatically generated and named as <code>onHandleText</code> (notice the <code>on</code> and the uppercase first letter of your signal's name - if you miss these two things your slot will never get triggered). This applies even to signals coming from C++ context. In our case we have <code>changeText(QString newText)</code> so the QML slot is automatically generated as <code>onChangeText</code>. Another thing that is important to remember is that you HAVE TO have a name for the argument(s) the C++ signal carries and that name has to be exactly what you use inside your QML slot which receives the C++ signal. If you write</p>
<pre><code>Text {
  ...
  Connections {
            target: commObject
            onChangeText: {
                textItem.text = msg;
            }
        }
}
</code></pre>
<p dir="auto">it will throw a <code>ReferenceError: msg is not defined</code> since internally <code>newText</code> is what is used to access the string that the C++ signal carries. Last but not least (yet another annoying thing) - the <code>target</code> in the <code>Connections</code> item is for the <strong>source of the signal</strong> (which in our case is the C++ <code>CommObject</code>). The naming is extremely confusing and I hope that they change it in future releases (I'm currently using Qt 5.7).</p>
<p dir="auto">You can easily adapt the examples above to your scenario. I decided to write it in a more general way for future reference.</p>
]]></description><link>https://forum.qt.io/post/343170</link><guid isPermaLink="true">https://forum.qt.io/post/343170</guid><dc:creator><![CDATA[Red Baron]]></dc:creator><pubDate>Sat, 20 Aug 2016 18:55:08 GMT</pubDate></item><item><title><![CDATA[Reply to communicating from c++ to qml on Fri, 19 Aug 2016 02:30:47 GMT]]></title><description><![CDATA[<p dir="auto">Hi <a class="plugin-mentions-user plugin-mentions-a" href="/user/sgaist">@<bdi>SGaist</bdi></a><br />
Thanks for you kind reply.I am actually using Q_PROPERTY in my c++ with read ,write and notify value but how to assign Q_PROPERTY in qml any small example will clear my doubt.<br />
Presently what i am doing is.</p>
<pre><code>//C++ class
//MyTestClass
Q_PROPERTY(int val READ val WRITE setValue NOTIFY valChanged)
//In main

//I am setting a root context and exposing this whole class.
//in Qml
//I have a button and in onClicked signal  i am able
// to access the data in c++ class.
</code></pre>
<p dir="auto">But I want to trigger my signal from C++ to qml , trigger in the sense without any click event in qml.</p>
<p dir="auto">Thank you</p>
]]></description><link>https://forum.qt.io/post/343106</link><guid isPermaLink="true">https://forum.qt.io/post/343106</guid><dc:creator><![CDATA[Shiv]]></dc:creator><pubDate>Fri, 19 Aug 2016 02:30:47 GMT</pubDate></item><item><title><![CDATA[Reply to communicating from c++ to qml on Thu, 18 Aug 2016 21:30:01 GMT]]></title><description><![CDATA[<p dir="auto">Hi,</p>
<p dir="auto">You can use a Q_PROPERTY for that for example and each time your value is changed emit the corresponding signal. Then in qml you'll assign that property to what you want to use to show its value.</p>
<p dir="auto">Hope it helps</p>
]]></description><link>https://forum.qt.io/post/343082</link><guid isPermaLink="true">https://forum.qt.io/post/343082</guid><dc:creator><![CDATA[SGaist]]></dc:creator><pubDate>Thu, 18 Aug 2016 21:30:01 GMT</pubDate></item></channel></rss>