Qt多线程回调函数简单案例
时间: 2023-05-22 17:02:42 浏览: 167
Sure, I'd be happy to help you with that question. Here is a simple example of a Qt multi-threaded program that demonstrates how to use callback functions:
```
#include <QtCore/QCoreApplication>
#include <QtCore/QThread>
class WorkerThread : public QThread {
Q_OBJECT
public:
WorkerThread(QObject* parent = nullptr) : QThread(parent) {}
protected:
void run() override {
// Do some work, and then call the callback function
int result = 123;
// Call the callback function with the result
callback(result);
}
public:
typedef void (*CallbackFunc)(int);
void setCallback(CallbackFunc func) {
callback = func;
}
private:
CallbackFunc callback;
};
void someCallback(int result) {
qDebug() << "Callback called with result:" << result;
}
int main(int argc, char* argv[]) {
QCoreApplication app(argc, argv);
WorkerThread thread;
thread.setCallback(someCallback);
thread.start();
return app.exec();
}
```
In this example, we create a WorkerThread class that inherits from QThread. We override the run() method to do some work and then call a callback function. We also define a typedef for the callback function, so we can easily pass it as a parameter to the setCallback() method.
In the main() function, we create an instance of the WorkerThread class, set the callback function using the setCallback() method, and start the thread using the start() method. The main() function then enters the Qt event loop using the app.exec() method.
When the WorkerThread instance runs, it will do some work and then call the callback function with a result value. The someCallback() function will be called with the result value and print it to the console.
I hope this simple example helps you understand how to use callbacks with multi-threaded Qt programs.
阅读全文