Reputation: 170
I basically just want to use multiple derived classes to change a member variable of a base class and to forward that value to qml using qproperty, but for some reason it's not working
car.h
#include <QObject>
class Car : public QObject{
Q_OBJECT
Q_PROPERTY(int seats MEMBER m_seats NOTIFY updateSeats)
public:
explicit Car(QObject *parent = 0);
~Car();
int m_seats;
Q_INVOKABLE void test();
signals:
void updateSeats();
};
car.cpp
#include "car.h"
Car::Car(QObject *parent) :
QObject(parent),
m_seats(0)
{
}
Car::test(){
m_seats = 5;
emit updateSeats();
}
Car::~Car(){}
toyota.h
#include "car.h"
class Toyota : public Car{
Q_OBJECT
public:
explicit Toyota(QObject *parent = 0);
~Toyota();
void foundCar();
};
toyota.cpp
#include "toyota.h"
Toyota::Toyota(QObject *parent)
{
}
Toyota::foundCar(){
m_seats = 4;
emit updateSeats();
}
Toyota::~Toyota(){}
Now, after invoking the foundCar function in class Toyota, if I do console.log(car.seats) in qml I get 0, but I expect it to be 4 because I am modifying it in the derived class. However if I call car.test() from qml and then I print car.seats, the value is 5. I am confused why this is the case. In qml I want car.seats to be 4. What am I missing?
Upvotes: 0
Views: 348
Reputation: 4582
Toyota
object is derived class object Toyota
of base Car
not an object of Car
you are modifying derived class object member Toyota::m_seats
and that won't have any effect on direct base Car
object .. and because Q_PROPERTY is defined only in base class Car
.. the only value QML would see is base class object .. and specifically the object you set in setContextProperty
... the code you omitted after the post edit.
From previous edits in your post, you seem to set the setContextProperty
in your engine as Car
object .. its in this object where you need to modify member that is a Q_PROPERTY.
I am referring to your code:
Car::startGui(){
QQmlApplicationEngine engine;
QQmlContext *ctxt = engine.rootContext();
ctxt->setContextProperty("car", this)
// start engine, which works properly
}
Upvotes: 1