在Qt中,可以使用信號和槽機制來在多線程之間傳遞參數。下面是一種常見的方法:
class Worker : public QObject
{
Q_OBJECT
public:
Worker() {}
public slots:
void doWork(int parameter)
{
// 處理參數
}
signals:
void workDone(int result);
};
QThread* thread = new QThread;
Worker* worker = new Worker;
// 將worker的doWork函數與thread的started信號連接
connect(thread, &QThread::started, worker, &Worker::doWork);
// 將worker的workDone信號與thread的quit和deleteLater槽連接
connect(worker, &Worker::workDone, thread, &QThread::quit);
connect(worker, &Worker::workDone, worker, &Worker::deleteLater);
// 將worker對象移動到工作線程
worker->moveToThread(thread);
// 啟動工作線程
thread->start();
class Sender : public QObject
{
Q_OBJECT
public:
Sender() {}
signals:
void sendParameter(int parameter);
};
Sender* sender = new Sender;
Worker* worker = new Worker;
// 將sender的sendParameter信號與worker的doWork槽連接
connect(sender, &Sender::sendParameter, worker, &Worker::doWork);
// 發送參數
int parameter = 42;
emit sender->sendParameter(parameter);
這樣,當sender發出sendParameter信號時,參數將通過信號和槽機制傳遞給worker的doWork函數進行處理。