问题描述
我无法给出一个非常简单的示例来开始使用Qt多线程.我读了很多文章和教程,但仍然行不通.
I cannot produce a very simple example to getting start with Qt multi-thread. I read a lot of posts and tutorials but still it doesn't work.
具有独立于GUI的后台工作者.哦,哇...
Have a background worker independent from the GUI. Oh, wow...
一个简单的例子:
- 创建
Engine
类 显示 - 并启动
QTimer
并打印数字
QMainWindow
的- create the
Engine
class - that shows a
QMainWindow
- and starts a
QTimer
that prints a number
但是如果您用鼠标左键单击GUI的标题栏,请按住鼠标按钮(即最小按钮)计数器将停止!即使它是在非GUI环境中创建的,并且已在另一个线程中移动!
But if you left-click the title bar of the GUI, keeping pressed the mouse button (i.e. on the minimize button) the counter will stop! Even if it was created in a non-GUI environment and it was moved in another thread!
main.cpp
#include "engine.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Engine e;
return a.exec();
}
engine.h
#ifndef ENGINE_H
#define ENGINE_H
#include <QObject>
#include <QThread>
#include <QTimer>
#include "mainwindow.h"
class Engine : public QObject
{
Q_OBJECT
public:
explicit Engine(QObject *parent = 0);
private:
MainWindow mainWindow;
QThread *thread;
QTimer *timer;
private slots:
void foo();
};
#endif // ENGINE_H
engine.c
#include "engine.h"
#include <QDebug>
Engine::Engine(QObject *parent) : QObject(parent)
{
thread = new QThread(this);
timer = new QTimer();
timer->setInterval(100);
connect(timer, &QTimer::timeout, this, &Engine::foo);
connect(thread, &QThread::started, timer, static_cast<void (QTimer::*)(void)>(&QTimer::start));
timer->moveToThread(thread);
thread->start();
mainWindow.show();
}
void Engine::foo()
{
static int i;
qDebug() << ++i;
}
QMainWindow
不包含任何代码.
推荐答案
基本上,Qt有一个处理GUI的线程(通常是主线程). GUI工作将阻止特定于此线程的任何对象.您需要将GUI保留在交互伙伴之外.
Basically, Qt has one thread dealing with the GUI (typically the main thread). Any objects specific to this thread will be blocked by GUI work. You need to keep the GUI outside of your interacting partners.
更具体地说,您的Engine
对象位于GUI/主线程中.即使您的计时器发送到工作线程中,它的信号也会分派到主线程中的插槽foo()
.
To be more specific, your Engine
object resides in the GUI/main thread. Even while your timer is sent to a worker thread, its signals are dispatched to the slot foo()
in the main thread.
您需要拆解Engine
和主窗口,以便Engine
可以驻留在其自己的线程中并在GUI阻塞时处理信号.
You need to de-mangle Engine
and the main window such that Engine
can reside in its own thread and process signals while the GUI is blocking.
这篇关于带有GUI的Qt多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!