Is it possible to use a factory class in C++ to create objects that can be accessed in QML? How can I access a newly created object in QML using JavaScript?
In my C++ factory class, I have implemented the creation of an employee
object, which can be of type Manager
, SalesPerson
, or Engineer
, all derived from the base class Employee
. Below is the code snippet:
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, I am facing a challenge in my QML script when trying to create and access an employee object.
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 and results in an 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
}
}