在Qt中,可以通過信號和槽機制來實現(xiàn)類之間的數(shù)據(jù)傳遞。以下是一種常見的方法:
signals
關鍵字定義一個信號。例如:class Sender : public QObject
{
Q_OBJECT
signals:
void dataReady(int data);
};
public slots
關鍵字定義一個槽函數(shù)。例如:class Receiver : public QObject
{
Q_OBJECT
public slots:
void receiveData(int data);
};
QObject::connect
函數(shù)來連接信號和槽函數(shù)。例如:Sender sender;
Receiver receiver;
QObject::connect(&sender, SIGNAL(dataReady(int)), &receiver, SLOT(receiveData(int)));
emit
關鍵字和信號函數(shù)來發(fā)送數(shù)據(jù)。例如:void Sender::sendData()
{
int data = 10;
emit dataReady(data);
}
void Receiver::receiveData(int data)
{
qDebug() << "Received data:" << data;
}
當發(fā)送數(shù)據(jù)的類調(diào)用Sender::sendData()
時,信號dataReady(int)
被觸發(fā),連接的槽函數(shù)Receiver::receiveData(int)
會被調(diào)用,接收到發(fā)送的數(shù)據(jù)并進行處理。