Qt 信号和槽 分析一
#ifndef COUNTER_H
#define COUNTER_H
#include <QObject>
class counter : public QObject
{
Q_OBJECT
public:
explicit counter(QObject *parent = 0);
int value() const;
private:
int m_value;
signals:
void valuechange(int);
public slots:
void setvalue(int);
};
#endif // COUNTER_H
#include "counter.h" #include <iostream> using namespace std; counter::counter(QObject *parent) : QObject(parent) { m_value=0; } int counter::value() const { return m_value; } void counter::setvalue(int newvalue) { if(m_value!=newvalue) { m_value=newvalue; emit valuechange(newvalue); } }
#include <QtCore/QCoreApplication> #include "counter.h" #include <iostream> using namespace std; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); counter app1,app2; QObject::connect(&app1,SIGNAL(valuechange(int)),&app2,SLOT(setvalue(int))); app1.setvalue(12); cout<<app1.value()<<" "<<app2.value()<<endl; app2.setvalue(24); cout<<app1.value()<<" "<<app2.value()<<endl; return a.exec(); }