Qt中最明显的特点就是采用信号槽机制,使得对象之间可以相互通信,传递消息,在前台界面开发中应用尤其广泛。
关联两个对象,要使用conncet函数,如下,sender发送一个signal信号,receiver就会执行method方法
QMetaObject::Connection QObject::connect(const QObject * sender, const char * signal, const \
QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection)
举一个例子
头文件
#ifndef SIGNALSLOTDEMO_H
#define SIGNALSLOTDEMO_H
#include <QObject>
class SignalSlotDemo : public QObject
{
Q_OBJECT
public:
explicit SignalSlotDemo(QObject *parent = 0);
int getValue();
signals:
void changedValue(int newValue);
public slots:
void setValue(int value);
private:
int value;
};
#endif // SIGNALSLOTDEMO_H
源文件
#include "signalslotdemo.h"
#include <iostream>
using namespace std;
SignalSlotDemo::SignalSlotDemo(QObject *parent) : QObject(parent),value()
{
}
int SignalSlotDemo::getValue()
{
return this->value;
}
void SignalSlotDemo::setValue(int value)
{
this->value = value;
emit changedValue(this->value);
}
测试文件
#include <QCoreApplication>
#include<iostream>
using namespace std;
#include "signalslotdemo.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
SignalSlotDemo demo1;
SignalSlotDemo demo2;
QObject::connect(&demo1, SIGNAL(changedValue(int)), &demo2, SLOT(setValue(int)));
demo1.setValue(200);
cout<<demo2.getValue()<<endl;
return a.exec();
}
demo1 在调用自己的成员方法setValue的时候,会发射一个changedValue信号(携带变量value),这时候demo2的setValue就会被调用了