QBasicTimer::start: Timers cannot be started from another thread
时间: 2024-01-14 11:41:43 浏览: 56
This error message occurs when you attempt to start a QBasicTimer object from a different thread than the one it was created in. QBasicTimer is designed to be used with the event loop of the thread it was created in, and it is not thread-safe.
To fix this error, you need to ensure that the QBasicTimer object is started from the same thread it was created in. You can do this by using signals and slots to communicate between threads, or by using a different type of timer that is designed to be used across multiple threads, such as QTimer.
Here is an example of using signals and slots to start a QBasicTimer from another thread:
```
// In the main thread:
QBasicTimer timer;
connect(&workerThread, &QThread::started, &timer, &QBasicTimer::start);
// In the worker thread:
void WorkerThread::run() {
// Do some work...
emit started();
// Do some more work...
}
```
In this example, the QBasicTimer object is created in the main thread and connected to the started signal of the worker thread. When the worker thread starts, it emits the started signal, which triggers the start method of the QBasicTimer object in the main thread.
Alternatively, you can use a QTimer object, which is designed to be used across multiple threads:
```
// In the main thread:
QTimer timer;
timer.moveToThread(&workerThread);
connect(&workerThread, &QThread::started, &timer, &QTimer::start);
// In the worker thread:
void WorkerThread::run() {
// Do some work...
// QTimer::start will now be called in the worker thread
}
```
In this example, the QTimer object is created in the main thread and moved to the worker thread using the moveToThread method. The started signal of the worker thread is connected to the start method of the QTimer object, which can now be safely called from the worker thread.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)