在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函数进行处理。