[Qt, C++] 클래스간 데이터 이동(Signal, Slot, connect)

테스트 환경

Windows10 / C++ / Qt 5.15.2 / Qt Creator 4.13.3

목적

Qt Creator를 활용, MainWindow 클래스에서 Test 클래스로 데이터를 이동시킨 후 Test클래스에서 이동된 데이터를 출력한다.

클래스 간 데이터 이동

새 클래스 생성

프로젝트를 우클릭 후 Add new를 클릭한다.

C++ Class를 선택한다.

Class name을 입력한다. 클래스 이름을 입력하면 헤더 파일과 소스파일은 자동적으로 이름이 입력된다.

클래스 이름은 아래 예제를 수행하기 위해 가급적 Test로 지정한다.

클래스 간 데이터 이동을 위한 slot과 signal을 사용하기 위해서는 QObject를 상속받아야 한다.

Add to project를 현재 실행 중엔 프로젝트로 지정한다.

mainwindow.h

mainwindow.h를 아래와 같이 수정한다.

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include "test.h"
#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    Test *test;

signals:
    void Send(int data);
};
#endif // MAINWINDOW_H

signal로 등록된 Send함수는 MainWindow에서 test클래스로 데이터를 보낼 함수이다.

Qt에서 클래스 간 통신은 signal과 slot로 이루어진다. signal은 데이터를 송신, slot은 수신하는 함수다. signal과 slot의 파라미터 자료형을 같게 하여 signal 함수의 파라미터 값을 slot 함수 파라미터 값으로 복사하는 방식으로 데이터가 이동된다.

test.h

test.h를 아래와 같이 수정한다.

#ifndef TEST_H
#define TEST_H

#include <QObject>
#include <QDebug>

class Test : public QObject
{
    Q_OBJECT
public:
    explicit Test(QObject *parent = nullptr);

private slots:
    void Receive(int data);
};

#endif // TEST_H

test클래스에서 데이터를 받을 함수는 Receive로 선언한다.

mainwindow.cpp

mainwindow.cpp를 아래와 같이 수정한다.

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    test = new Test(this);
    connect(this, SIGNAL(Send(int)), test, SLOT(Receive(int)));

    for(int i=0;i<10;i++)
    {
        emit Send(i);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

connect 함수는 만들어둔 Send함수와 Receive함수를 연결시킨다.

connect(보낼 클래스, SIGNAL(보낼 함수(파라미터), 받을 클래스, SLOT(받을 함수(파라미터)))

emit을 사용하여 Send함수를 송신한다. 위 코드는 스레드 클래스로 0부터 9까지 순차적으로 송신시킨다.

test.cpp

test.cpp를 아래와 같이 수정한다.

#include "test.h"

Test::Test(QObject *parent) : QObject(parent)
{

}

void Test::Receive(int data)
{
    qDebug() << data;
}

MainWindow 함수에서 Send로 데이터를 송신하면 Receive 함수가 수행된다. 아래 코드는 수신받은 데이터를 곧바로 출력한다.

결과 확인

0부터 9까지 순차적으로 출력되는 것을 확인할 수 있다.

Leave a Comment