Как setContextProperty () терпит неудачу в этой ситуации? - PullRequest
1 голос
/ 22 мая 2019

У меня есть три класса, созданные в C ++ как Window, PropertyList и MyParams, и я хочу передать PropertyList и MyParams эти два класса в qml.

class Window
{
public:
    PropertyList* getPropertyList();
private:
    PropertyList* propertyList;
};

class PropertyList : public QObject
{
    Q_OBJECT
public:
    MyParams* getMyParams();
    Q_INVOKABLE void test();

private:
    MyParams* myParams;
};

class MyParams : public QObject
{
    Q_OBJECT
public:
    Q_INVOKABLE void test();
};

int main(int argc, char *argv[])
{
    Window* window = new Window();
    PropertyList* propertyList = window->getPropertyList();
    MyParams* myParam = propertyList->getMyParams();

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty(QStringLiteral("myParams"), myParam);

    engine.rootContext()->setContextProperty(QStringLiteral("propertyList"), propertyList);
}

Почему это работает:

engine.rootContext()->setContextProperty(QStringLiteral("propertyList"), propertyList);

И эта ошибка:

 engine.rootContext()->setContextProperty(QStringLiteral("myParams"), myParam);

Это потому, что я объявляю PropertyList как Q_OBJECT?И как я могу это исправить?Большое спасибо.

propertyList.test () может быть успешно вызван, в то время как myParams.test () не может быть вызван и произошел сбой qml.

1 Ответ

2 голосов
/ 22 мая 2019

Я не вижу никаких проблем в вашем примере кода, потому что образец не завершен (Обратите внимание: https://stackoverflow.com/help/reprex).

Тем не менее, я реализовал решение для вас. Надеюсь, это поможет. ( Предупреждение: будут утечки памяти вокруг класса Window, но он должен помочь понять привязку C ++ и Qml)

Вот ваш PropertyList.h:

#ifndef PROPERTYLIST_H
#define PROPERTYLIST_H

#include "myparams.h"

#include <QObject>

class PropertyList : public QObject
{
    Q_OBJECT
public:
    explicit PropertyList(QObject *parent = nullptr) : QObject (parent) { }

    MyParams* getMyParams()
    {
        return  myParams;
    }

    Q_INVOKABLE void test()
    {
        qDebug() << "PropertyList test";
    }

private:
    MyParams* myParams = new MyParams();
};

#endif // PROPERTYLIST_H

Вотваш MyParams.h:

#ifndef MYPARAMS_H
#define MYPARAMS_H

#include <QObject>
#include <QDebug>

class MyParams : public QObject
{
    Q_OBJECT
public:
    explicit MyParams(QObject *parent = nullptr) : QObject (parent) { }

    Q_INVOKABLE void test()
    {
        qDebug() << "MyParams test";
    }
};

#endif // MYPARAMS_H

Вот ваш main.cpp:

#include "propertylist.h"

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlEngine>
#include <QQmlContext>
#include <QDebug>

class Window
{
public:
    PropertyList* getPropertyList()
    {
        return propertyList;
    }

private:
    PropertyList* propertyList = new PropertyList(nullptr);
};

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    Window* window = new Window();
    PropertyList* propertyList = window->getPropertyList();
    MyParams* myParam = propertyList->getMyParams();

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty(QStringLiteral("myParams"), myParam);

    engine.rootContext()->setContextProperty(QStringLiteral("propertyList"), propertyList);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
    {
            return -1;
    }

    return app.exec();
}

Вот ваш main.qml:

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    ColumnLayout {
        anchors.centerIn: parent
        Button {
            text: "myParams"
            onClicked: {
                myParams.test()
            }
        }

        Button {
            text: "propertyList"
            onClicked: {
                propertyList.test()
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...