这很简单。请看下面的例子。
如果你想在自己的类中编写信号和插槽,你需要满足两个条件......
1. Your class must inherit from QObject class or any class derived from QObject.
2. The Q_OBJECT macro must appear in a private section in your class.
/* Sender.h */
#ifndef SENDER_H
#define SENDER_H
#include <QObject>
class Sender : public QObject
{
Q_OBJECT
public:
explicit Sender(QObject *parent = 0);
void fireSignal();
signals:
void foo(const QString& arg);
};
#endif // SENDER_H
/* Sender.cpp*/
#include "Sender.h"
Sender::Sender(QObject *parent) :
QObject(parent)
{
}
void Sender::fireSignal()
{
emit foo("This a message sender is sending to receiver.");
}
现在接收者的代码如下
/* Receiver.h */
#ifndef RECEIVER_H
#define RECEIVER_H
#include <QObject>
class Receiver : public QObject
{
Q_OBJECT
public:
explicit Receiver(QObject *parent = 0);
public slots:
void bar(const QString& arg);
};
#endif // RECEIVER_H
/* Receiver.cpp */
#include "Receiver.h"
#include <iostream>
Receiver::Receiver(QObject *parent) :
QObject(parent)
{
}
void Receiver::bar(const QString &arg)
{
std::cout << arg.toStdString();
}
现在 main.cpp 代码
#include <QtCore/QCoreApplication>
#include "Sender.h"
#include "Receiver.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Sender sender;
Receiver receiver;
QObject::connect(&sender, SIGNAL(foo(QString)), &receiver, SLOT(bar(QString)));
sender.fireSignal();
return a.exec();
}
就是这样。
最后,如果您想对连接方法使用另一种语法。请使用以下几行
QObject::connect(&sender,&Sender::foo,&receiver,&Receiver::bar);
希望这对您有所帮助。谢谢