2015-06-07 131 views
1

我想单击按钮时更改矩形的颜色。它们都在main.qml文件中。我想向C++后端发送一个信号来改变矩形的颜色。我似乎无法从文档中提供的代码搞清楚将信号QML连接到C++(Qt5)

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
QPushButton *mybutton = engine.findChild("mybutton"); 

首先,通过QObject::findChild对象名称找到的QObject,不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 *

+0

'QList 对象= engine.rootObjects();' 'QPushButton *为myButton =' 'Object.first() - > findChild( “myButton的”);' 此代码仍然给我一个错误消息:“没有匹配函数调用“ 我已经将objectName属性添加到按钮。 – user3927312

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"; 
}