在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)
會被調用,接收到發送的數據并進行處理。