main.cpp
#include "Counter.h"
#include <QtCore/QDebug>
void Counter::setValue(int value)
{
if (value != m_value)
{
m_value = value;
emit valueChanged(value);
}
}
int main(void)
{
Counter a, b;
QObject::connect(&a, SIGNAL(valueChanged(int)), &b, SLOT(setValue(int)));
a.setValue(12); // a.value() == 12, b.value() == 12
b.setValue(48); // a.value() == 12, b.value() == 48
qDebug() << "a value " << a.value();
qDebug() << "b value " << b.value();
return 0;
}
Counter.h
#pragma once
#include <QtCore/QObject>
class Counter : public QObject
{
Q_OBJECT
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;
};
demo.pro
QT += core
TARGET = qtdemo
SOURCES += main.cpp
CONFIG += console
HEADERS += Counter.h
编译运行
mkdir build && cd build
qmake .. && make