我想在C++中使用工厂类来创建可在QML中使用/访问的对象。但是,如何在QML中访问这种新创建的对象?这是可能的JavaScript?如何在C++中创建对象并在QML中访问它
在C++我的工厂类创建一个对象employee
其可以是Manager
,SalesPerson
或Engineer
类型的所有从Employee
的。这里是代码:
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();
}
现在在我的QML代码中,我想创建员工并访问它。
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
}
}
有错字管线'雇员E = factory.createEmployee(0)'。使用'员工'。 – vcp
@vcp如果我执行'employee'而不是错误地运行,但是如果我在下一行访问它,则表示'employee is not defined'。 – zar
不要忘记在QML'import MyModel 1.0'中导入语句。 – vcp