zoukankan      html  css  js  c++  java
  • qml stackview在堆栈,导致connect无法连接

    我有多个QML文件可以通过StackView进行推送。如何将它们连接到C+?

    • 回答 (2)
    • 关注 (0)
    • 查看 (235)

    我的项目包含6个qml文件:main.qml打开一个新的ApplicationWindow并声明工具栏。它还使用initalItem homescreen.qml初始化StackView。在主屏幕上,我有不同的按钮,通过stack.push(“URL”)打开不同的qml文件。除了main.qml之外,所有文件都以Item {}开头。我已经能够连接main.qml和home.qml中的信号。但是我无法访问堆栈中更深层的对象。我不知道是否需要更改我的.cpp代码来访问其他对象,或者我是否应该更改StackView的初始化,以便在开始时加载和访问所有文件。这是代码,分解为非常基础:

    • main.qml ApplicationWindow { Rectangle{ id: homeButton objectName: "homeButton" signal qmlSignal(string msg) MouseArea { onClicked: {stack.push({item:"qrc:/home.qml}); homeButton.qmlSignal("Hello")} } } StackView{ initalItem: "qrc:/home.qml" } }
    • secondframe.qml //主屏幕后面的randomw qml文件 Item { Rectangle{ id: test objectName: "test" signal qmlSignal(string msg) MouseArea { onClicked: {stack.push({item:"qrc:/thirdframe.qml}); test.qmlSignal("Hello")} } } }
    • main.cpp中 QApplication app (argc, argv); QQmlEngine enigne; QQmlComponent component(&engine, QUrl(QStringLiteral("qrl:/main.qml"))); QObject *object = componet.create(); QQmlComponent newcomponent(&engine, QUrl(QStringLiteral("qrl:/secondframe.qml"))); QObject *newobject = newcomponet.create(); MyClass myClass QObject *home = object->findChild<QObject*>("homeButton"); // I'm able to connect to every Object in the main.qml or home.qml QObject::connect(home,SIGNAL(qmlSignal(Qstring)), &myClass, SLOT(cppSlot(QString))); QObject *test = newobject->findChild<QObject*>("test"); // Can't connect to the Objects in secondframe.qml QObject::connect(test,SIGNAL(qmlSignal(Qstring)), &myClass, SLOT(cppSlot(QString)));
    • 回答1:

    一种比进入QML树并提取可能存在或可能不存在的对象更好的方法是为QML提供基于C ++的API。

    1. 创建一个基于QObject的类,它具有QML需要能够作为插槽或调用的方法 Q_INVOKABLE class MyAPI : public QObject { Q_OBJECT public slots: void cppSlot(const QString &text); };
    2. 创建一个实例并将其公开给QML MyAPI myApi; QQmlEngine engine; engine.rootContext()->setContextProperty("_cppApi", &myApi);
    3. 在QML中使用,就像“_cppApi”是对象id一样 MouseArea { onClicked: {stack.push({item:"qrc:/thirdframe.qml}); _cppApi.cppSlot("Hello")} }:

    回答2:

    在堆栈上按qml之后,对象将是可访问的。因此,当你发出一些信号时,当对象将在堆栈上时,解决方案可以如下所示:

    MyClass myClass
    QObject *home = object->findChild<QObject*>("homeButton");    // I'm able to connect to every Object in the main.qml or home.qml
    QObject::connect(home,SIGNAL(qmlSignal(Qstring)), &myClass, SLOT(cppSlot(QString)));
    
    connect( myClass, MyClass::emitWhenQMLIsAlreadyOnTheStack, this, [this](){
        QObject *test = newobject->findChild<QObject*>("test");       // Now you should be able to connect
        QObject::connect(test,SIGNAL(qmlSignal(Qstring)), &myClass, SLOT(cppSlot(QString));
    });
  • 相关阅读:
    js实现对身份证校验
    zip解压缩
    zip压缩
    文件内容编解码
    文件的操作
    Mysql账号管理
    深度优先算法DFS
    Java常见知识问答
    Hibernate的单向OneToMany、单向ManyToOne
    Angularjs在线编辑器
  • 原文地址:https://www.cnblogs.com/wxmwanggood/p/11046358.html
Copyright © 2011-2022 走看看