QML Dynamic insertions of components in loader from C++ - c++

I've fully edit my question since I've made some progress, and the first one was unclear.
I use Qt 4.8, with QtQuick 1.0.
I have a page where I need to keep the top and the bottom margin. So I've defined a Main.qml like that :
Item {
id: salesWindow
width: 800
height: 600
[...] //Properties def
TopBar {[...]}
CloseButton{[...]}
Rectangle {[...]}
//I want to load qml file in this loader. The QML file loaded use some of the Main.qml properties
Loader {
id: appPlaceHolder
objectName: "loader"
anchors.centerIn: parent
}
Rectangle {[...]}
BotBar {[...]}
}
If I put a qml file into the loader sourceComponent, it works.
Now I want to do it with C++, and well designed. I've subclass QDeclarativeComponent in SalesAppDisplay.h
class SalesAppDisplay : public IDisplayScreen
{
Q_OBJECT
static const std::string QML_FILENAME;
static const std::string QML_DIR_PATH;
public:
SalesAppDisplay(DisplayContext& context, QDeclarativeEngine& engine, QObject* parent = 0);
~SalesAppDisplay();
void doScreenInit();
const std::string getQmlFilename() const;
};
class IDisplayScreen : public QDeclarativeComponent
{
Q_OBJECT
[...]
}
and the Ctor in charge of component instanciation :
IDisplayScreen::IDisplayScreen(DisplayContext& context, QDeclarativeEngine& engine, std::string qmlFilepath, QObject* parent)
: QDeclarativeComponent(&engine, QString(qmlFilepath.c_str()), parent)
Instead of loading a qml file in the loader by changing the source, I want to insert my component into the QML from main.cpp :
m_view.setSource(QUrl::fromLocalFile("../displaymanager/rsrc/qml/Main.qml"));
QObject* mainObj = m_view.rootObject();
[ .. Set file property ]
//this is the component subclass instantiation (made by factory)
m_currentScreen = displaymanager::createDisplayScreen(IDisplayScreen::SALESAPP, *(m_context), *(m_view.engine()), mainObj);
QDeclarativeItem* saleAppObj = qobject_cast<QDeclarativeItem*>(m_currentScreen->create(m_view->rootContext()));
saleAppObj->setParentItem(qobject_cast<QDeclarativeItem*>(mainObj));
[ .. Set file property ]
//I can find my loader without any problems
QDeclarativeItem *loader = mainObj->findChild<QDeclarativeItem*>("loader");
/* I don't know what to do here for making it works */
m_view.show();
m_qApp.exec();
I've tried loader->setProperty("sourceComponent", qobject_cast<QVariant>(saleAppObj));, and some other tricks like that without any results.
I have errors from my saleApp.qml saying that he don't know Main.qml properties that i used in it (he is clearly load at the Components instanciation). And despite that main.qml is perfectly loaded, nothing from SaleApp.qml appears.

I have made it work.
There is the screen handling function :
void QtDisplayManager::switchScreen(int screenID)
{
if(m_currentScreen)
{
m_currentScreen->destroyItem();
}
//App screen creation
m_currentScreen = displaymanager::createDisplayScreen(screenID, m_context, *m_engine, m_mainObj);
//Get App placehoder
QDeclarativeItem* loaderItem = m_mainObj->findChild<QDeclarativeItem*>("loader");
//Put app in placeholder
if(loaderItem)
{
m_currentScreen->getItem()->setParentItem(loaderItem);
m_engine->clearComponentCache();
m_context.setcurrentDisplayID(screenID);
}
}
destroyItem() is a function I've add to delete item pointer without deleting the whole component, just because I had a problem where the component was not removed from the view when a new was added.
SalesApp.qml have no reference on the MainWindow.qml, so I have add two wrapper :
m_view.rootContext()->setContextProperty("managerWrapper", this);
m_view.rootContext()->setContextProperty("appWrapper", m_currentScreen);
Works perfectly, design is good, code is sweet.

Related

Creating a Nested Custom QML Component `Component` in a C++ Class

The Problem
I am trying to create a QML Component (and by component, I mean a QML component of type Component that gets used by a Loader's sourceComponent property) in a C++ class and pass it down to a QML File. I am using a Loader particularly to dynamically change a single area of the view based on user interaction with the UI elsewhere on that view. Here is how I am approaching the implementation:
DynamicLoader.h
class DynamicLoader: public QQuickItem {
Q_OBJECT
Q_PROPERTY(QObject *mainComp READ getMainComp NOTIFY mainCompChanged)
public:
DynamicLoader(QQuickItem *parent = Q_NULLPTR);
QObject* getMainComp() const;
private:
QObject* m_mainComp;
QObject* createComponent();
signals:
void mainCompChanged();
};
DynamicLoader.cpp
DynamicLoader::DynamicLoader(QQuickItem* parent)
: QQuickItem(parent)
, m_mainComp(new QObject(this)) {
m_mainComp = createCustomComponent();
}
QObject *DynamicLoader::getMainComp() const {
return m_mainComp;
}
QObject* DynamicLoader::createComponent() {
QQmlEngine engine;
QQmlComponent component(&engine,
QUrl::fromLocalFile("://imports/components/CustomComponent.qml"));
QObject* object = component.create();
Q_ASSERT(object);
QQuickItem* childItem = qobject_cast<QQuickItem*>(object);
childItem->setParent(this);
return childItem;
}
CustomComponent.qml
Component {
CustomTextBox {
text: "Custom Text"
}
}
CustomTextBox.qml
import QtQuick 2.0
Item {
property int containerWidth: 580
property alias text: customText.text
anchors.fill: parent
Text {
id: customText
text: "Default Text"
anchors.top: parent.top
anchors.horizontalCenter: parent.horizontalCenter
width: parent.width
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
font.weight: Font.Bold
font.pointSize: 100
color: "white"
}
}
This, however, crashes the program with the following error message:
QQmlComponent: Component is not ready, and fails at the Q_ASSERT.
Other Findings
This same error occurs even when CustomComponent.qml is changed to simply Component {}. When I discovered this, I suspected that perhaps QQmlComponent already wraps the QML file with a Component type (please correct me if I am wrong), so I went ahead and converted the file to:
Item {
CustomTextBox {
text: "Custom Text"
}
}
and got the same error.
Only when I change the file to the following does it not error out:
Item {
Item {
}
}
Lastly, the error does not occur when I implement CustomComponent.qml entirely in QML.
Questions
Am I correct in thinking that declaring a QQmlComponent already wraps a QML file with the Component type? If not, how should I be creating a Component QML component in C++?
Why does the program crash when I create a nested custom component? Do I need to create the component through other means?
Any help and corrections to fundamental misconceptions would be greatly appreciated. Thank you.

Safely deleting QML component being used in StackView transition

Overview
My question deals with the lifetime of a QObject created by QQmlComponent::create(). The object returned by create() is the instantiation of a QQmlComponent, and I am adding it to a QML StackView. I am creating the object in C++ and passing it to QML to display in the StackView. The problem is that I am getting errors when I pop an item from the stack. I wrote a demo app to illustrate what's happening.
Disclaimer: Yes, I know that reaching into QML from C++ is not "best practice." Yes, I know that you should do UI stuff in QML. However, in the production world, there is a ton of C++ code that needs to be shared with the UI, so there needs to be some interop between C++ and CML. The primary mechanism I'm using is Q_PROPERTY bindings by setting the context on the C++ side.
This screen is what the demo looks like when it starts:
The StackView is in the center with a gray background and has one item in it (with the text 'Default View'); this item is instantiated and managed by QML. Now if you press the Push button, then the C++ back-end creates an object from ViewA.qml and places it on the stack...here is a screen shot showing this:
At this point, I press Pop to remove "View A" (in red in the picture above) from the StackView. C++ calls into QML to pop the item from the stack and then deletes the object it created. The problem is that QML needs this object for the transition animation (I'm using the default animation for StackView), and it complains when I delete it from C++. So I think I understand why this is happening, but I'm not sure how to find out when QML is done with the object so I can delete it. How can I make sure QML is done with an object that I created in C++ so I can safely delete it?
Summarizing, here are the steps that reproduce the problem I am describing:
Start program
Click Push
Click Pop
The following output shows the TypeErrors that happen when the item is popped in step 3 above:
Output
In the output below, I press "Push" once, then I press "Pop". Note the two TypeErrors when ~ViewA() is called.
root object name = "appWindow"
[c++] pushView() called
qml: [qml] pushView called with QQuickRectangle(0xdf4c00, "my view")
[c++] popView() called
qml: [qml] popView called
[c++] deleting view
~ViewA() called
file:///opt/Qt5.8.0/5.8/gcc_64/qml/QtQuick/Controls/Private/StackViewSlideDelegate.qml:97: TypeError: Cannot read property 'width' of null
file:///opt/Qt5.8.0/5.8/gcc_64/qml/QtQuick/Controls/StackView.qml:899: TypeError: Type error
Context must be set from C++
Clearly, what is happening is that the object (item) that the StackView is using is being deleted by C++, but QML still needs this item for the transition animation. I suppose I could create the object in QML and let the QML engine manage the lifetime, but I need to set the QQmlContext of the object to bind the QML view to Q_PROPERTYs on the C++ side.
See my related question on Who owns object returned by QQmlIncubator.
Code Example
I've generated a minimally complete example to illustrate the problem. All files are listed below. In particular, look at the code comments in ~ViewA().
// main.qml
import QtQuick 2.3
import QtQuick.Controls 1.4
Item {
id: myItem
objectName: "appWindow"
signal signalPushView;
signal signalPopView;
visible: true
width: 400
height: 400
Button {
id: buttonPushView
text: "Push"
anchors.left: parent.left
anchors.top: parent.top
onClicked: signalPushView()
}
Button {
id: buttonPopView
text: "Pop"
anchors.left: buttonPushView.left
anchors.top: buttonPushView.bottom
onClicked: signalPopView()
}
Rectangle {
x: 100
y: 50
width: 250
height: width
border.width: 1
StackView {
id: stackView
initialItem: view
anchors.fill: parent
Component {
id: view
Rectangle {
color: "#DDDDDD"
Text {
anchors.centerIn: parent
text: "Default View"
}
}
}
}
}
function pushView(item) {
console.log("[qml] pushView called with " + item)
stackView.push(item)
}
function popView() {
console.log("[qml] popView called")
stackView.pop()
}
}
// ViewA.qml
import QtQuick 2.0
Rectangle {
id: myView
objectName: "my view"
color: "#FF4a4a"
Text {
text: "View A"
anchors.centerIn: parent
}
}
// viewa.h
#include <QObject>
class QQmlContext;
class QQmlEngine;
class QObject;
class ViewA : public QObject
{
Q_OBJECT
public:
explicit ViewA(QQmlEngine* engine, QQmlContext* context, QObject *parent = 0);
virtual ~ViewA();
// imagine that this view has property bindings used by 'context'
// Q_PROPERTY(type name READ name WRITE setName NOTIFY nameChanged)
QQmlContext* context = nullptr;
QObject* object = nullptr;
};
// viewa.cpp
#include "viewa.h"
#include <QQmlEngine>
#include <QQmlContext>
#include <QQmlComponent>
#include <QDebug>
ViewA::ViewA(QQmlEngine* engine, QQmlContext *context, QObject *parent) :
QObject(parent),
context(context)
{
// make property bindings visible to created component
this->context->setContextProperty("ViewAContext", this);
QQmlComponent component(engine, QUrl(QLatin1String("qrc:/ViewA.qml")));
object = component.create(context);
}
ViewA::~ViewA()
{
qDebug() << "~ViewA() called";
// Deleting 'object' in this destructor causes errors
// because it is an instance of a QML component that is
// being used in a transition. Deleting it here causes a
// TypeError in both StackViewSlideDelegate.qml and
// StackView.qml. If 'object' is not deleted here, then
// no TypeError happens, but then 'object' is leaked.
// How should 'object' be safely deleted?
delete object; // <--- this line causes errors
delete context;
}
// viewmanager.h
#include <QObject>
class ViewA;
class QQuickItem;
class QQmlEngine;
class ViewManager : public QObject
{
Q_OBJECT
public:
explicit ViewManager(QQmlEngine* engine, QObject* topLevelView, QObject *parent = 0);
QList<ViewA*> listOfViews;
QQmlEngine* engine;
QObject* topLevelView;
public slots:
void pushView();
void popView();
};
// viewmanager.cpp
#include "viewmanager.h"
#include "viewa.h"
#include <QQmlEngine>
#include <QQmlContext>
#include <QDebug>
#include <QMetaMethod>
ViewManager::ViewManager(QQmlEngine* engine, QObject* topLevelView, QObject *parent) :
QObject(parent),
engine(engine),
topLevelView(topLevelView)
{
QObject::connect(topLevelView, SIGNAL(signalPushView()), this, SLOT(pushView()));
QObject::connect(topLevelView, SIGNAL(signalPopView()), this, SLOT(popView()));
}
void ViewManager::pushView()
{
qDebug() << "[c++] pushView() called";
// create child context
QQmlContext* context = new QQmlContext(engine->rootContext());
auto view = new ViewA(engine, context);
listOfViews.append(view);
QMetaObject::invokeMethod(topLevelView, "pushView",
Q_ARG(QVariant, QVariant::fromValue(view->object)));
}
void ViewManager::popView()
{
qDebug() << "[c++] popView() called";
if (listOfViews.count() <= 0) {
qDebug() << "[c++] popView(): no views are on the stack.";
return;
}
QMetaObject::invokeMethod(topLevelView, "popView");
qDebug() << "[c++] deleting view";
auto view = listOfViews.takeLast();
delete view;
}
// main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQuickView>
#include <QQuickItem>
#include "viewmanager.h"
#include <QDebug>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQuickView view;
view.setSource(QUrl(QLatin1String("qrc:/main.qml")));
QObject* item = view.rootObject();
qDebug() << "root object name = " << item->objectName();
ViewManager viewManager(view.engine(), item);
view.show();
return app.exec();
}
I'm posting an answer to my own question. If you post an answer, I'll consider accepting your answer instead of this one. But, this is a possible work-around.
The problem is that a QML object that is created in C++ needs to live long enough for the QML engine to complete all transitions. The trick I'm using is to mark the QML object instance for deletion, wait a few seconds for QML to finish the animation, and then delete the object. The "hacky" part here is that I have to guess how many seconds I should wait until I think that QML is completely finished with the object.
First, I make a list of objects that are scheduled to be destroyed. I also make a slot that will be called after a delay to actually delete the object:
class ViewManager : public QObject {
public:
...
QList<ViewA*> garbageBin;
public slots:
void deleteAfterDelay();
}
Then, when the stack item is popped, I add the item to garbageBin and do a single-shot signal in 2 seconds:
void ViewManager::popView()
{
if (listOfViews.count() <= 0) {
qDebug() << "[c++] popView(): no views are on the stack.";
return;
}
QMetaObject::invokeMethod(topLevelView, "popView");
// schedule the object for deletion in a few seconds
garbageBin.append(listOfViews.takeLast());
QTimer::singleShot(2000, this, SLOT(deleteAfterDelay()));
}
After a few seconds, the deleteAfterDelay() slot is called and "garbage collects" the item:
void ViewManager::deleteAfterDelay()
{
if (garbageBin.count() > 0) {
auto view = garbageBin.takeFirst();
qDebug() << "[c++] delayed delete activated for " << view->objectName();
delete view;
}
}
Aside from not being 100% confident that waiting 2 seconds will always be long enough, it seems to work extremely well in practice--no more TypeErrors and all objects created by C++ are properly cleaned up.
I believe I have identified a way to ditch the garbage list that #Matthew Kraus recommended. I let QML handle destroying the view while popping out of the StackView.
warning: Snippets are incomplete and only meant to illustrate extension to OP's post
function pushView(item, id) {
// Attach option to automate the destruction on pop (called by C++)
rootStackView.push(item, {}, {"destroyOnPop": true})
}
function popView(id) {
// Pop immediately (removes transition effects) and verify that the view
// was deleted (null). Else, delete immediately.
var old = rootStackView.pop({"item": null, "immediate": true})
if (old !== null) {
old.destroy() // Requires C++ assigns QML ownership
}
// Tracking views in m_activeList by id. Notify C++ ViewManager that QML has
// done his job
viewManager.onViewClosed(id)
}
You will quickly find that the interpreter yells at you on delete if the object was created, and still owned, by C++.
m_pEngine->setObjectOwnership(view, QQmlEngine::JavaScriptOwnership);
QVariant arg = QVariant::fromValue(view);
bool ret = QMetaObject::invokeMethod(
m_pRootPageObj,
"pushView",
Q_ARG(QVariant, arg),
Q_ARG(QVariant, m_idCnt));

Invoking c++ slots from plasmoid qml

New question for you guys.
I have a simple kde (kf5) plasmoid, with a label and two buttons.
I have a C++ class behind the scenes, and I am currently able to send signals from C++ to qml.
The problem: I need to send signals from the qml buttons to the C++ class.
Usually this could be done by using the standard Qt/qml objects like QQuickView and so on, but in my case I have no main.cpp.
This is my C++ class header. Using a QTimer, I emit the textChanged_sig signal, which tells the qml to refresh the label's value:
class MyPlasmoid : public Plasma::Applet
{
Q_OBJECT
Q_PROPERTY(QString currentText READ currentText NOTIFY textChanged_sig)
public:
MyPlasmoid( QObject *parent, const QVariantList &args );
~MyPlasmoid();
QString currentText() const;
signals:
void textChanged_sig();
private:
QString m_currentText;
}
This is the plasmoid main.qml:
import QtQuick 2.1
import QtQuick.Layouts 1.1
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.plasma.plasmoid 2.0
import org.kde.plasma.components 2.0 as PlasmaComponents
Item {
Plasmoid.fullRepresentation: ColumnLayout {
anchors.fill: parent
PlasmaComponents.Label {
text: plasmoid.nativeInterface.currentText
}
PlasmaComponents.Button {
iconSource: Qt.resolvedUrl("../images/start")
onClicked: {
console.log("start!") *** HERE
}
}
}
}
The PlasmaComponents.Label item contains the correct value of the c++ field m_currentText.
*** HERE I need to emit some signal (or invoke a c++ method, would have the same effect).
Any hint?
Since you can access the currentText property through plasmoid.nativeInterface that object is almost certainly an instance of your C++ applet class, i.e. a MyPlasmoid instance.
So if your MyPlasmoid has a slot, it can be called as a function on the plasmoid.nativeInterface object
in C++
class MyPlasmoid : public Plasma::Applet
{
Q_OBJECT
public slots:
void doSomething();
};
in QML
onClicked: plasmoid.nativeInterface.doSomething()

Qt: onChildrenChanged not launched when QML components are created at runtime from C++ code

For a project, I need to create QML components at runtime from C++.
My general architecture is the following:
Project1:
Engine.h
Engine.cpp
CustObject.h
CustObject.cpp
Plugin.h
Plugin.cpp
Dummy.qml
Project2:
main.cpp
main.qml
What I want to do is instantiate Engine.cpp as a QML object (possible since I registered it in the Plugin class and made it available to Project2) and then create dynamically CustObject instances (which are also registered to be used by Project2) from Engine. In the end I want that if I write:
ApplicationWindow{
id: window
visible: true
Engine{
id: eng1
CustObject{
id: custObj1
}
}
}
This will be the same as writing something like
ApplicationWindow {
id: window
visible: true
Button {
text: "add new child"
onClicked: {
console.log("QML: Number children before", eng1.children.length);
eng1.addNewChildren();
console.log("QML: Number children after", eng1.children.length);
}
}
Engine{
id: eng1
onChildrenChanged: console.log("Changed")
}
}
And I should see that the number of children is incremented and onChildrenChanged from eng1 should be launched.
The problem is that neither the number of children is incremented, nor the signal onChildrenChanged is launched.
I had also the other problem that in order to add a children to the parent, eng1 in my case, I used the function QQmlComponent(QQmlEngine *engine, const QUrl &url, QObject *parent = 0) of QQMLComponent class. But I cannot find a way to transform my CustObject class into a QUrl since it is not a .qml file.
Therefore I first tried to add a dummy qml object called: Dummy.qml instead of CustObject object. Dummy.qml looks like this:
import QtQuick 2.0
Item {
property int nb: 1
}
The code of my Engine class looks like this:
Engine.h:
#ifndef ENGINE_H
#define ENGINE_H
#include <QQuickItem>
#include <QQmlComponent>
#include <QQmlEngine>
#include <QQmlContext>
class Engine : public QQuickItem{
Q_OBJECT
public:
explicit Engine(QQuickItem* parent = 0);
virtual ~Engine();
Q_INVOKABLE QObject* addNewChildren();
};
#endif // ENGINE_H
Engine.cpp:
#include "Engine.h"
Engine::Engine(QQuickItem* parent) :
QQuickItem(parent)
{
}
Engine::~Engine(){ }
QObject* Engine::addNewChildren(){
qDebug() << "CPP: Number children before " << this->children().size();
QObject* parentEntity = this;
QQmlComponent* childrenEntity;
QQmlComponent component(qmlEngine(this), QUrl("qrc:///src/Dummy.qml"));
QQuickItem *childrenItem = qobject_cast<QQuickItem*>(component.create());
QQmlEngine::setObjectOwnership(childrenItem, QQmlEngine::CppOwnership);
childrenItem->setParent(parentEntity);
childrenItem->setProperty("nb", 2);
qDebug() << "CPP: Number children after" << this->children().size();
//qDebug() << "Property value:" << QQmlProperty::read(childrenItem, "nb").toInt();
return childrenItem;
}
But my output when I run main.qml is the following:
qml: QML: Number children before 0
CPP: Number children before 0
CPP: Number children after 1
qml: QML: Number children after 0
And I commented the line corresponding to QQmlProperty::read due to the following error: "incomplete type 'QQmlProperty' used in nested name specifier
qDebug() << "Property value:" << QQmlProperty::read(childrenItem, "nb").toInt();"
^
I have therefore the following questions:
Why is the number of children incrementation not seen from qml (but visible from cpp)?
Why is onChildrenChanged not launched from qml?
How can I add dynamically CustObject class (which is visible as a qml object from Project2 point of view since it is registered)
instead of Dummy.qml?
How to read a property of a dynamically added object in C++ just after its creation (i.e. how to use QQMlProperty::read)?
Thank you a lot in advance for any help you could give me!
Why is the number of children incrementation not seen from qml (but visible from cpp)?
QML doesn't use QObject::children(), instead it uses QQuickItem::childItems(). Yes, that's right, there are two different list of children, one from QObject, and one from QQuickItem. Both serve different purposes: The one from QObject is mainly for memory management (children get deleted when parent gets deleted), while the one from QQuickItem is for the 'visual hierachy', e.g. children get drawn on top of their parent. More details are available in the docs.
Why is onChildrenChanged not launched from qml?
Because the onChildrenChanged is only emitted when QQuickItem::childItems() changes, which it doesn't. Call setParentItem() in addition to setParent() to fix that.
How can I add dynamically CustObject class (which is visible as a qml object from Project2 point of view since it is registered) instead of Dummy.qml?
By simply creating the object yourself and setting the parent and parentItem. There is no need to use QQmlComponent here.
QObject childrenItem = new CustObject();
childrenItem->setParent(parentEntity);
childrenItem->setParentItem(parentEntity);
How to read a property of a dynamically added object in C++ just after its creation (i.e. how to use QQMlProperty::read)?
Calling QQuickItem::childItems() should do the trick, no need to read a property. FWIW, there probably was an #include <QQmlProperty> missing in the code that didn't work.

Communication between C++ and QML

This page shows how to call C++ functions from within QML.
What I want to do is change the image on a Button via a C++ function (trigger a state-change or however it is done).
How can I achieve this?
UPDATE
I tried the approach by Radon, but immediately when I insert this line:
QObject *test = dynamic_cast<QObject *>(viewer.rootObject());
Compiler complains like this:
error: cannot dynamic_cast '((QMLCppBinder*)this)->QMLCppBinder::viewer.QDeclarativeView::rootObject()' (of type 'struct QGraphicsObject*') to type 'class QObject*' (source is a pointer to incomplete type)
In case it is relevant, QMLCppBinder is a class that I try to build to encapsulate the connections from several QML pages to C++ code. Which seems to be trickier than one might expect.
Here is a skeleton class to give some context for this:
class QMLCppBinder : public QObject
{
Q_OBJECT
public:
QDeclarativeView viewer;
QMLCppBinder() {
viewer.setSource(QUrl("qml/Connect/main.qml"));
viewer.showFullScreen();
// ERROR
QObject *test = dynamic_cast<QObject *>(viewer.rootObject());
}
}
If you set an objectName for the image, you can access it from C++ quite easy:
main.qml
import QtQuick 1.0
Rectangle {
height: 100; width: 100
Image {
objectName: "theImage"
}
}
in C++:
// [...]
QDeclarativeView view(QUrl("main.qml"));
view.show();
// get root object
QObject *rootObject = dynamic_cast<QObject *>(view.rootObject());
// find element by name
QObject *image = rootObject->findChild<QObject *>(QString("theImage"));
if (image) { // element found
image->setProperty("source", QString("path/to/image"));
} else {
qDebug() << "'theImage' not found";
}
// [...]
→ QObject.findChild(), QObject.setProperty()
So, you could set your C++ object as a context property on the QDeclarativeView in C++, like so:
QDeclarativeView canvas;
ImageChanger i; // this is the class containing the function which should change the image
canvas.rootContext()->setContextProperty("imgChanger", &i);
In your ImageChanger class, declare a signal like:
void updateImage(QVariant imgSrc);
Then when you want to change the image, call emit updateImage(imgSrc);.
Now in your QML, listen for this signal as follows:
Image {
id: imgToUpdate;
}
Connections {
target: imgChanger;
onUpdateImage: {
imgToUpdate.source = imgSrc;
}
}
Hope this helps.