[英]QT C++ to QML can not be connected
我有以下代碼:
class Boundaries: public QObject{
Q_OBJECT
enum Type{
in,
out
};
QDateTime m_startTimeBoundary{};
QDateTime m_endTimeBoundary{};
QDateTime m_from{};
QDateTime m_to{};
Q_PROPERTY(QDateTime fromDate READ getFromDate NOTIFY emitSignal1)
Q_PROPERTY(QDateTime toDate READ getToDate NOTIFY emitSignal1)
QDateTime getFromDate(){
return m_from;
}
QDateTime getToDate(){
return m_to;
}
public: signals:
void emitSignal1();
public:
void initBoundaries(const QDateTime& start,const QDateTime& end){
if (m_startTimeBoundary.isNull() && m_endTimeBoundary.isNull()){
m_startTimeBoundary = start;
m_endTimeBoundary = end;
}
}
void myClass(const QDateTime& origin, qint64 diffMs, Type type)
{
//..some code..
emit emitSignal1();
}
Q_INVOKABLE void myClassIn(const QDateTime& origin, qint64 diffMs){
myClass(origin, diffMs, Type::in);
}
Q_INVOKABLE void myClassOut(const QDateTime& origin, qint64 diffMs){
myClass(origin, diffMs, Type::out);
}
};
我的 C++ model:
class MyCustomModel: public QObject{
Q_OBJECT
..some code..
Q_PROPERTY(Boundaries* myClass READ getmyClass)
Boundaries* m_myClass;
Boundaries* getmyClass(){
return m_myClass;
}
.. some other code..
}
我的 QML 連接問題來了:
MyButton {
anchors.verticalCenter: timeFilterRow.verticalCenter
onClicked:{
var x = getDataX()
var y = getDataY()
myCustomModel.myClass.myClassIn(_org, diff)
}
}
但我得到一個錯誤,說Boundaries
是未知的。 你們中的任何人都可以幫助我理解我在這里做錯了什么嗎? 還是我錯過了什么?
您是否曾經創建過類型為Boundaries
的 object ?
Declaring a pointer in C or C++ doesn't automatically instantiate the object and the member isn't even default initialized to nullptr
, so it could be any address to memory. 如果真的是這樣,你很幸運它沒有崩潰。 如果您在調試模式下在正確的平台上使用了正確的編譯器,則指針會自動初始化為nullptr
。
Qml reads from the type information (QMetaObject, https://doc.qt.io/qt-5.14/qmetaobject.html ) which invokables/slots/properties are available. 如果指針為nullptr
,則 Qml 無法訪問該 object 的類型信息,因為它不存在。
下一點:如果你想在Q_PROPERTY
中使用它,你必須使用 Qt 類型系統注冊你的類型:
Q_DECLARE_METATYPE(Boundaries)
https://doc.qt.io/qt-5.14/qmetatype.html#Q_DECLARE_METATYPE
Qt 將屬性類型打包到QVariant
中(查看類型擦除模式)。 要使用它,您必須告訴 Qt,您的類型將需要它的代碼(默認情況下,它不會為您定義的所有類生成代碼,嚴格符合“您只需為使用的內容付費” )。
To my understanding with myCustomModel.myClass.myClassIn(_org, diff)
you are trying to invoke a function of an object from your C++ environment but you are actually creating a new instance of type MyCustomModel
which requires QML to know of the class Boundaries
而不是注冊類型( qmlRegisterType
)以使其可實例化,我猜您正在尋找一種方法來傳遞您的 C++ object 以使其在 ZC477ABFB7FD4959A20D5E0240ADC26B0 中可訪問
如果是這種情況,您可以通過聲明上下文屬性來實現:
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
MyCustomModel model;
engine.rootContext()->setContextProperty(QStringLiteral("modelinstance"), &model);
engine.load(QUrl(QStringLiteral("qrc:/main.qml"));
return app.exec();
}
然后您應該能夠從 QML 中調用此 object 實例:
if (modelinstance)
modelinstance.myclass.myClassIn(_org, diff)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.