I want to use a factory class in C++ to create objects which I can use/access in QML. But how do I access such newly created object in QML? Is this possible with the javascript?
My factory class in C++ creates an employee
object which can be either Manager
, SalesPerson
or Engineer
type all derived from Employee
. Here is the code:
class EmployeeFactory : public QObject
{
Q_OBJECT
public:
enum
{
MANAGER,
SALES_PERSON,
ENGINEER
};
explicit EmployeeFactory(QObject *parent = 0);
Q_INVOKABLE Employee *createEmployee(int type)
{
if (type == MANAGER )
{
qDebug() << "createEmployee(): Manager created";
return new Manager;
}
else if(type == SALES_PERSON)
{
qDebug() << "createEmployee(): SalesPerson created";
return new SalesPerson;
}
else if(type == ENGINEER)
{
qDebug() << "createEmployee(): Engineer created";
return new Engineer;
}
qDebug() << "createEmployee(): Nothing created";
return 0;
}
signals:
public slots:
};
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
EmployeeFactory * factory = new EmployeeFactory;
qmlRegisterType<Employee>("MyModel", 1, 0, "employee");
engine.rootContext()->setContextProperty("factory", factory);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
Now in my QML code, I want to create the employee and access it.
Window {
visible: true
MouseArea {
anchors.fill: parent
onClicked: {
// how do I access the return value `employee` here or how
// do I return/access employee here
employee e = factory.createEmployee(0) // This doesn't work, result in Expected token ';' error
// once I have the employee, I would like to set its attributes like
// e.name: "David"
}
}
Text {
text: qsTr("Hello World")
anchors.centerIn: parent
}
}