简体   繁体   English

从C ++调用QML方法

[英]Invoke QML method from C++

I want to invoke a method in MyMap from my class MyBacklogg , how do I do this when I don't have the object parameters in that class? 我想从类MyBacklogg调用MyMap的方法, MyMap该类中没有对象参数时该怎么做?

I'm going to receive a string, a QByteArray or a QDataStream in MyBacklogg , depending on which one that works the best, and I want to pass these along to my GUI. 我将在MyBacklogg接收一个字符串,QByteArray或QDataStream,具体取决于哪个字符串最有效,我想将它们传递给我的GUI。

main.cpp: main.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: 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: 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));
    ??????????????????????????????
}

Did you try initializing MyBacklogg by passing the object pointer to it and preserving it as a class member? 您是否尝试过通过将object指针传递给MyBacklogg并将其保留为类成员来初始化MyBacklogg

Although if you are calling QML functions from C++, in 99.9% of the cases you are doing it wrong. 尽管如果从C ++调用QML函数,则在99.9%的情况下,这样做是错误的。

The proper solution would be to emit a signal from C++ and install a handler for it on the QML side. 正确的解决方案是从C ++发出信号,并在QML端为其安装处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM