我基本上只是想使用多个派生类来更改基类的成员变量,并使用qproperty将其值转发到qml,但是发出信号无效,并且我无法使信号静态< / p>
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();
static int m_seats;
signals:
void updateSeats();
};
car.cpp
#include "car.h"
Car::Car(QObject *parent) :
QObject(parent)
{
}
int Car::m_seats = 0;
Car::~Car(){}
toyota.h
#include "car.h"
class Toyota : public Car{
Q_OBJECT
public:
explicit Toyota(QObject *parent = 0);
~Toyota();
Q_INVOKABLE void foundCar();
};
toyota.cpp
#include "toyota.h"
Toyota::Toyota(QObject *parent)
{
}
Toyota::foundCar(){
m_seats = 4;
emit updateSeats(); // This isn't working
}
Toyota::~Toyota(){}
main.cpp
#include <QGuiApplication>
#include "car.h"
#include "toyota.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
Car car = new Car();
Toyota ty = new Toyota();
QQmlApplicationEngine engine;
QQmlContext *ctxt = engine.rootContext();
ctxt->setContextProperty("car", car);
ctxt->setContextProperty("toyota", ty);
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
app.exec();
engine.quit();
}
在qml中,当我调用foundCar函数后打印car.seats时
main.qml
toyota.foundCar()
console.log(car.seats)
输出仍为0。发出的信号未更新的原因可能是因为它来自其他对象(丰田)。那么如何从派生类发出基类的信号呢?
答案 0 :(得分:1)
您的toyota
和car
属性是两个单独的属性。
您必须从seats
阅读toyota
属性:
main.qml
toyota.foundCar()
console.log(toyota.seats) //<--- here
评论后更新:
好吧,这是另一种方法,但是在那种情况下,我将car
属性设置为Toyota指针:
main.cpp
Car car = new Toyota();
ctxt->setContextProperty("car", ty);
ctxt->setContextProperty("toyota", ty);
这可能适合一个总体类(类似于car_manager
或car_store
),在该类中,您具有可用汽车的列表以及选择一个汽车作为当前汽车的功能,然后进行更新该总体类的通用car
或current
属性。
之所以这样说,是因为当您要从根上下文工作时,您会得到讨厌的代码,此外,根属性不会表明它们已更改