我在理解如何使用 qml 中的 c 單例物件時遇到問題。我知道我必須從 QObject 類繼承我的類并且我必須公開屬性。為了讓它們在 qml 中可用,我必須執行 setContextProperty("ClassName", &class name)。
但是,如果我們承認這個類包含另一個物件并且我希望能夠從 qml 中使用它,我會從未定義的物件中收到類似“無法呼叫方法名稱”的錯誤。
例子:
API.h
class API : public QObject {
Q_OBJECT
Q_PROPERTY(User *user READ getUser WRITE setUser NOTIFY userChanged)
public:
Q_INVOKABLE inline User *getUser() const {
qDebug() << "get called";
return user;
};
inline void setUser(User *new_user) { this->user = new_user; };
signals:
void userChanged();
private:
User *user;
};
用戶.h
#ifndef USER_H
#define USER_H
#include <QObject>
#include <QString>
class User: public QObject{
Q_OBJECT
public:
Q_INVOKABLE inline QString &getName(){return name;}; // qrc:/main.qml:63: TypeError: Cannot call method 'getName' of undefined
private:
QString name;
};
#endif // USER_H
主檔案
#include <QQmlContext>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQuick3D/qquick3d.h>
#include "API.h"
#include "User.h"
int main(int argc, char *argv[]) {
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
API api;
User user;
api.setUser(&user);
engine.rootContext()->setContextProperty("API", &api);
qmlRegisterType<User>("User", 1, 0, "User");
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
main.qml
import QtQuick
import QtQuick3D
import QtQuick.Controls
import QtQuick.Layouts
Window {
Item{
id: test
Component.onCompleted: {
console.log("Completed")
API.getUser() // no error, getUser is called without error
console.log(API.getUser().getName())
}
}
}
我必須通過 API 從 qml 訪問 User 物件有哪些可能性?
uj5u.com熱心網友回復:
您可以執行以下任何操作:
在 API 類中添加一個公共插槽:
API.cpp:
QString API::getUserName()
{
return user.getName();
}
main.qml:
Component.onCompleted: console.log( API.getUserName() )
使用戶成為 API 類中的 Q_PROPERTY:
API.h:
Q_PROPERTY( User* user READ user NOTIFY userChanged)
main.qml:
Component.onCompleted: console.log( API.user.getName() )
向 QML 注冊用戶:
main.cpp:
qmlRegisterType<User>("MyUser", 1, 0, "MyUser");
main.qml:
Component.onCompleted: console.log( API.getUser().getName() )
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414844.html
標籤:
上一篇:將QWidget添加到QGridLayout會為布局添加邊框?
下一篇:QLineEdit:無法顯示
