带有GUI的Qt多线程 [英] Qt multi-thread with GUI

查看:374
本文介绍了带有GUI的Qt多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法给出一个非常简单的示例来开始使用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
  • 显示QMainWindow
  • 并启动QTimer并打印数字
  • 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多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆