상세 컨텐츠

본문 제목

[C++ QT QML] Signal slot 활용하여 화면 클릭 시 이벤트 처리

QT|QML

by donggyu1998 2021. 6. 15. 11:33

본문

반응형

이 예제는 signal slot을 활용하여 QML에서 화면 클릭 시 문구를 출력하는 예제입니다.

💡 실행 사진

💡 Main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "receiver.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    Receiver receiver;

    QQmlContext* ctx = engine.rootContext();
    ctx->setContextProperty("receiver", &receiver);
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

    receiver.sendToQml(43);

    return app.exec();
}

코드 : https://pastebin.com/jFVY9HVb

 

💡 receiver.h

#ifndef RECEIVER_H
#define RECEIVER_H

#include <QObject>

class Receiver : public QObject
{
    Q_OBJECT
public:
    explicit Receiver(QObject *parent = 0);

signals:
    void sendToQml(int count);

public slots:
    void receiveFromQml(int count);

};

#endif // RECEIVER_H

💡 receiver.cpp

#include "receiver.h"
#include <QDebug>

Receiver::Receiver(QObject *parent) :
    QObject(parent)
{
}

void Receiver::receiveFromQml(int count) {
    qDebug() << "Received in C++ from QML:" << count;
}

💡 main.qml

import QtQuick 2.2
import QtQuick.Window 2.1

Window {
    id: test
    visible: true
    width: 400
    height: 500

    Connections {
        target: receiver
        onSendToQml: {
            console.log("Received in QML from C++: " + count)
        }
    }

    MouseArea {
        anchors.fill: parent
        onClicked: { // 마우스 터치 시 QML 에서 C++로 통신
            receiver.receiveFromQml(42);
        }
    }

    Text {
        text: qsTr("Press me to send a signal to C++")
        anchors.centerIn: parent
    }
}

💡 signal_slot.pro

TEMPLATE = app

QT += qml quick

SOURCES += main.cpp \
    receiver.cpp

RESOURCES += qml.qrc

# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Default rules for deployment.
include(deployment.pri)

HEADERS += \
    receiver.h
반응형

관련글 더보기