2015-06-07 129 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"; 
}