将信号QML连接到C ++(Qt5)

时间:2015-06-07 20:12:47

标签: c++ qml qt5

我想在单击按钮时更改矩形的颜色。它们都在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();
}

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

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

首先,QObject::findChild通过对象名称找到QObjects,而不是id(无论如何都是上下文的本地)。因此,在QML中你需要类似的东西:

objectName: "mybutton"

其次,我认为您需要执行findChild而不是引擎本身,而是执行从QQmlApplicationEngine::rootObjects()返回的根对象。

// assuming there IS a first child
engine.rootObjects().at(0)->findChild<QObject*>("myButton"); 

第三,QML中的Button由您在C ++中不可用的类型表示。因此,您无法将结果分配给QPushButton *,但您需要坚持使用通用QObject *

答案 1 :(得分:0)

我必须创建一个单独的类和头文件,然后将它连接到main.cpp中的信号

的main.cpp

#include <QApplication>
#include <QQmlApplicationEngine>
#include<QtDebug>
#include <QQuickView>
#include<QPushButton>
#include<myclass.h>


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



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

    QObject *topLevel = engine.rootObjects().at(0);

    QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);

    MyClass myClass;

    QObject::connect(window,
                     SIGNAL(mysignal()),
                     &myClass,
                     SLOT(cppSlot())
                     );


    return app.exec();
}

myclass.h

#ifndef MYCLASS
#define MYCLASS



#include <QObject>
#include <QDebug>

class MyClass : public QObject
{
    Q_OBJECT

public slots:
    void cppSlot();

};
#endif // MYCLASS

myclass.cpp

#include<myclass.h>

void MyClass::cppSlot(){

    qDebug()<<"Trying";
}