我想在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