在QML中为C ++类型的QObject *属性赋值null时断言失败

时间:2014-09-06 08:57:58

标签: c++ qt qml

当我取消注释下面的一行时,我得到一个断言:

  

ASSERT:"!from.isNull()&& !to.isNull()"在文件[...] \ qtdeclarative \ src \ qml \ qml \ qqmlpropertycache.cpp,第1586行

#include <QGuiApplication>
#include <QtQml>
#include <QtQuick>

class Inventory : public QObject
{
    Q_OBJECT
public:
    Inventory() {
    }
};

class InventoryModel : public QObject
{
    Q_OBJECT
    Q_PROPERTY(Inventory *inventory READ inventory WRITE setInventory NOTIFY inventoryChanged)
public:
    InventoryModel() : mInventory(0) {
    }

    Inventory *inventory() const {
        return mInventory;
    }

    void setInventory(Inventory *inventory) {
        if (inventory != mInventory) {
            mInventory = inventory;
            emit inventoryChanged();
        }
    }
signals:
    void inventoryChanged();
private:
    Inventory *mInventory;
};

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

//    qRegisterMetaType<Inventory*>();
    qmlRegisterType<InventoryModel>("Qml", 1, 0, "InventoryModel");

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

    return app.exec();
}

#include "main.moc"

main.qml:

import QtQuick 2.3
import QtQuick.Controls 1.2

import Qml 1.0

ApplicationWindow {
    id: window
    visible: true
    width: 640
    height: 480

    InventoryModel {
        inventory: null
    }
}

我用Qt 5.4构建(qtdeclarative位于f9ee33f9683a4cd4d1a2e41efa6e8d124e9d731d)。可能导致这种情况的任何想法?

1 个答案:

答案 0 :(得分:2)

请尝试使用qmlRegisterType:

qmlRegisterType<Inventory>("Qml", 1, 0, "Inventory");

断言可能与此bug

有关