Programming/qt

qt6 시그널

구차니 2026. 3. 30. 11:14
#include <QObject>

class Counter : public QObject
{
    Q_OBJECT

// Note. The Q_OBJECT macro starts a private section.
// To declare public members, use the 'public:' access modifier.
public:
    Counter() { m_value = 0; }

    int value() const { return m_value; }

public slots:
    void setValue(int value);

signals:
    void valueChanged(int newValue);

private:
    int m_value;
};

void Counter::setValue(int value)
{
    if (value != m_value) {
        m_value = value;
        emit valueChanged(value);
    }
}

 

Counter a, b;
QObject::connect(&a, &Counter::valueChanged, &b, &Counter::setValue);

a.setValue(12);     // a.value() == 12, b.value() == 12
b.setValue(48);     // a.value() == 12, b.value() == 48

[링크 : https://doc.qt.io/qt-6/ko/signalsandslots.html]

[링크 : https://doc.qt.io/qt-6/ko/moc.html]

 

QT5(람다) / QT4 - 근데 람다 쓴다고 receiver도 사라질수 있나? this 어디갔지?

Qt 5 이상 스타일 (람다 함수 지원)
connect(sender, &Sender::signal, receiver, &Receiver::slot);

// 람다 함수 연결
connect(button, &QPushButton::clicked, []() {
    qDebug() << "Button clicked!";
});
 

Qt 4 이하 스타일
connect(sender, SIGNAL(signalName()), receiver, SLOT(slotName()));

[링크 : https://cagongman.tistory.com/109]

 

// new style
connect(&myObject, &SignalSlot::valueChanged, this, &Widget::setValue);

// old style
//connect(&myObject, SIGNAL(valueChanged(int)), this, SLOT(setValue(int)));

[링크 : https://dongyeop00.tistory.com/78]

[링크 : https://truelightn.tistory.com/6]