0

我想MyMap从我的类中调用一个方法,MyBacklogg当我在该类中没有对象参数时,我该怎么做?

我将收到一个字符串,一个 QByteArray 或一个 QDataStream in MyBacklogg,这取决于哪个效果最好,我想将它们传递给我的 GUI。

主.cpp:

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

    QQmlApplicationEngine engine;
    engine.load(QUrl(QLatin1String("qrc:/qml/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    QObject *item = engine.rootObjects().first();
    MyTcpSocket s;
    s.init();
    QObject::connect(item, SIGNAL(sendSignal()), &s, SLOT(doSlot()));

    return app.exec();
}

main.qml:

ApplicationWindow {
    id: appWindow
    visible: true
    height: 600
    width: 800
    title: qsTr("MyApp")
    signal sendSignal()

    RowLayout{
        visible: true
        anchors.fill: parent

        MyMap {
            id: mapview
            function myFunc() {
                //function called from MyBacklogg
            }
            function myOtherFunc() {
                sendSignal()
            }
        }
    }
}

MyBacklogg.cpp:

#include "mybacklogg.h"

MyBacklogg::MyBacklogg(QObject *parent) :
    QObject(parent)
{
}

void MyBacklogg::init()
{
    //initialize
}

void MyBacklogg::doSlot()
{
    //function call from MyMap
}

void MyBacklogg::callMethod()
{
    ??????????????????????????????
    QMetaObject::invokeMethod(object, "myFunc",
        Q_RETURN_ARG(QVariant, returnedValue),
        Q_ARG(QVariant, msg));
    ??????????????????????????????
}
4

1 回答 1

3

MyBacklogg您是否尝试通过将object指针传递给它并将其保留为类成员来进行初始化?

虽然如果你从 C++ 调用 QML 函数,在 99.9% 的情况下你做错了。

正确的解决方案是从 C++ 发出一个信号并在 QML 端为它安装一个处理程序。

于 2017-11-30T12:35:29.633 回答