我想在单击按钮时更改矩形的颜色。它们都在main.qml文件中。我想向C++后端发送信号以更改矩形的颜色。我似乎无法从文档中给出的代码中弄清楚

main.qml:
导入QtQuick 2.4
导入QtQuick.Controls 1.3
导入QtQuick.Window 2.2
导入QtQuick.Dialogs 1.2

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


    id:root

    signal mysignal()


    Rectangle{
     anchors.left: parent.left
     anchors.top: parent.top
     height : 100
     width : 100
    }

    Button
    {

        id: mybutton
        anchors.right:parent.right
        anchors.top:parent.top
        height: 30
        width: 50
     onClicked:root.mysignal()

    }

}

main.cpp:
#include <QApplication>
#include <QQmlApplicationEngine>
#include<QtDebug>
#include <QQuickView>

class MyClass : public QObject
{
    Q_OBJECT
public slots:
    void cppSlot() {
        qDebug() << "Called the C++ slot with message:";
    }
};

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

  MyClass myClass;

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

    QPushButton *mybutton = engine.findChild("mybutton");

    engine.connect(mybutton, SIGNAL(mySignal()),
                   &myClass, SLOT(cppSlot()));

    return app.exec();
}

任何帮助,将不胜感激!

最佳答案



首先,QObject::findChild通过对象名而不是id(无论如何对于上下文来说都是本地的)找到QObjects。因此,在QML中,您需要以下内容:

objectName: "mybutton"

其次,我认为您不需要在引擎本身上而是在从findChild返回的根对象上执行QQmlApplicationEngine::rootObjects()
// assuming there IS a first child
engine.rootObjects().at(0)->findChild<QObject*>("myButton");

第三,QML中的Button用C++中没有的类型表示。因此,您不仅可以将结果分配给QPushButton *,还需要坚持使用通用QObject *

关于c++ - 将Signal QML连接到C++(Qt5),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30697996/

10-12 00:11
查看更多