How to alter the properties of qml using Cpp.
-
Below I have written my code, I would like to change the child property of "rect" for ex. the color of the child rectangle. If i give the change in main.qml only the parent object is changed the child rectangle remains unchanged... Kindly help me pleaseeeee
-
MyItem.qml
@
Rectangle{
width: 400; height:400 color:"white" property string i:"asdff" property int j:25 property int u:0 signal clicked() Rectangle { id:rect2 objectName: rect; anchors.top: parent.top anchors.topMargin: 45 anchors.left: parent.left anchors.leftMargin: 35 anchors.right: parent.right anchors.rightMargin: 50 height: 30 radius: 8 color:"grey"
}}
@[Edit: Added @ tags and deleted duplicate post. You can edit previous posts rather than reposting. -- mlong]
-
Main.cpp
@#include <QtCore/QCoreApplication>
#include <QtGui/QApplication>
#include <QDeclarativeView>
#include <QDeclarativeProperty>
#include <QGraphicsObject>
#include <QObject>
#include "MyClass.h"
#include <QDebug>
#include <QDeclarativeContext>int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QDeclarativeView view;
view.setSource(QUrl::fromLocalFile("Test.qml";);
QObject *object1 = view.rootObject();/// insert code here//
MyClass myClass;
view.rootContext()->setContextProperty("object", &myClass);
view.show();
return app.exec();
}
@ -
@#ifndef MYCLASS_H
#define MYCLASS_H
#include <QtGui/QApplication>
#include <QDeclarativeView>
#include <QDeclarativeProperty>
#include <QGraphicsObject>
#include <QObject>
#include "MyClass.h"
#include <QDebug>
#include <QDeclarativeContext>class MyClass : public QObject
{
Q_OBJECTpublic:
Q_INVOKABLE void cppMethod(const QString &msg) {qDebug() << "FROM QML" << msg; }
public:
Q_INVOKABLE void cppMethod1(int abc=100) {
qDebug() << abc;}
public slots:
void cppSlot(int number) {
qDebug() << "Function call from QML" << number;
}
};
#endif // MYCLASS_H
@ -
Now, I want to change the color of rect2 from grey to red, how can this be done from .cpp file. Kindly give me a working solution. Thanks for your help:)
-
Would be much nicer to get just a condensed code from you. This amount is a tad too much, especially when it's commented-out in large amount of places.
Now that you have your C++ clas registered with QML, it's quite simple:
@
// in rect2
onClicked: {
color = object.getNewColor();
}
@And in C++:
@
// MyClass, public section
Q_INVOKABLE QString getNewColor() { return QString("#aabbcc"); }
@Just a quick draft, but should work.
-
thanks for your reply and suggestioon... but i would like to change the child using the setproperty in main .qml
-
Rather than an invokable method, create a Q_PROPERTY in your C++ class which has a getter, a setter, and a notify signal.