defaultK

[Qt 프로그래밍] qml, cpp 간 signal , slot 연결 본문

Qt 프로그래밍/Basic Qt

[Qt 프로그래밍] qml, cpp 간 signal , slot 연결

kwoss2341 2021. 2. 24. 20:54

 

MyClass.h

#ifndef MYCLASS_H
#define MYCLASS_H

#include <QObject>
#include <QDebug>

class MyClass : public QObject
{
    Q_OBJECT

private:

    
    public slots:
    void cppslot(const int a,const int b); // slot 정의



    public:
    MyClass(){

        //생성자~~

    }

    ~MyClass(){

        //소멸자~~

    }




};

#endif // COUNTER_H

 

MyClass.cpp

#include "MyClass.h"
#include <QObject>

void MyClass::cppslot(const int a,const int b)
{
   //slgnal을 통해 받은 a,b를 이용하여
   //slot을 구현하는 부분



}

 

 

main.cpp

/*

...

*/

QObject *object = engine.rootObjects()[0];

MyClass myClass;
QObject::connect(object,SIGNAL(qmlSignal(int,int)), &myClass, SLOT(cppslot(int,int)));

 

 

main.qml

Window {

    visible: true
    id: w1
    width: 640
    height: 480 
    title: qsTr("Hello World") 
    
    /* 시그널 정의 */
    signal qmlSignal(int op, int mod)

//중략........
RadioButton {
                                 objectName: "op11"           //option 1-1
                                 text: "option 1-1"
                                 
                                 onClicked: {
                                     w1.qmlSignal(1,1);
                                 }
             }                    
//.......

RadioButton {
                                 objectName: "op12"           //option 1-2
                                 text: "option 1-2"
                                 
                                 onClicked: {
                                     w1.qmlSignal(1,2);
                                 }
             }                    
  
  
//........ 

}
 

 

main.cpp의 object에 qml을 연동한 후

//QObject *object = engine.rootObjects()[0]; 

 

connect를 해준다.

//QObject::connect(object,SIGNAL(qmlSignal(int,int)), &myClass, SLOT(cppslot(int,int)));

 

connect는 qml에서 정의된 qmlSignal이 발생하면 myClass 객체의 slot인 cppslot() 메소드가 구현되는 방식이다. 

Comments