在Qt中,可以通过信号和槽机制来实现类之间的数据传递。以下是一种常见的方法:
signals
关键字定义一个信号。例如:class Sender : public QObject
{
Q_OBJECT
signals:
void dataReady(int data);
};
public slots
关键字定义一个槽函数。例如:class Receiver : public QObject
{
Q_OBJECT
public slots:
void receiveData(int data);
};
QObject::connect
函数来连接信号和槽函数。例如:Sender sender;
Receiver receiver;
QObject::connect(&sender, SIGNAL(dataReady(int)), &receiver, SLOT(receiveData(int)));
emit
关键字和信号函数来发送数据。例如:void Sender::sendData()
{
int data = 10;
emit dataReady(data);
}
void Receiver::receiveData(int data)
{
qDebug() << "Received data:" << data;
}
当发送数据的类调用Sender::sendData()
时,信号dataReady(int)
被触发,连接的槽函数Receiver::receiveData(int)
会被调用,接收到发送的数据并进行处理。