在Qt中将函数发送到主线程执行

考虑这样一种需求,使用Qt的线程类QThread在后台执行操作(比如说拷贝文件)的时候发生了错误,产生了一个错误信息需要提醒给用户,在后台输出很显然是不够的,因为用户可能根据就没有任何控制台可供程序输出信息。

这是本人自己做得一个仿Win10文件拷贝对话框的一个文件拷贝对话框

该问题纠结到根本是因为Qt的任何窗口代码都必须在主线程(也就是main函数所在的那个线程)中执行。如果在后台发生错误需要出对话框提示给用户的话,必须能够将后台信息阻塞性的发送给前台,在前台图形类的程序执行完毕后再返回。

那么在Qt中前后台如何通信呢,由于QThread是继承自QObject的,很自然大家会想到使用信号槽来连接:

bool QObject::connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection )

相信大家对于以上connect函数的定义是非常熟悉了,关键在于最后一个参数“Qt::ConnectionType”,以下是该参数的详细说明:

Qt::DirectConnection
When emitted, the signal is immediately delivered to the slot.
假设当前有4个slot连接到QPushButton::clicked(bool),当按钮被按下时,QT就把这4个slot按连接的时间顺序调用一遍。显然这种方式不能跨线程(传递消息)。

Qt::QueuedConnection
When emitted, the signal is queued until the event loop is able to deliver it to the slot.
假设当前有4个slot连接到QPushButton::clicked(bool),当按钮被按下时,QT就把这个signal包装成一个 QEvent,放到消息队列里。QApplication::exec()或者线程的QThread::exec()会从消息队列里取消息,然后调用 signal关联的几个slot。这种方式既可以在线程内传递消息,也可以跨线程传递消息。

Qt::BlockingQueuedConnection
Same as QueuedConnection, except that the current thread blocks until the slot has been delivered. This connection type should only be used for receivers in a different thread. Note that misuse of this type can lead to dead locks in your application.
与Qt::QueuedConnection类似,但是会阻塞等到关联的slot都被执行。这里出现了阻塞这个词,说明它是专门用来多线程间传递消息的。

Qt::AutoConnection
If the signal is emitted from the thread in which the receiving object lives, the slot is invoked directly, as with Qt::DirectConnection; otherwise the signal is queued, as with Qt::QueuedConnection.
这种连接类型根据signal和slot是否在同一个线程里自动选择Qt::DirectConnection或Qt::QueuedConnection

很显然在不同的线程间发送信号还希望发送信号的一端必须阻塞性的等待槽函数返回,那么“Qt::BlockingQueuedConnection”是我们的不二之选。

连接方式有了,然后是数据共享的问题,试想“后台线程中的数据如何能够被前台所使用,而且前台后台不一定在一个类里面?把数据打包通过信号传给前台?”想想就是很麻烦的事情,难道每个这样的需求场合都要做一遍这样的事情吗?感谢时间,因为时间穿过2011年,C++的新标准已经完美的解决了这个问题,那就是函数对象。

Qt的4.8.6版本所使用的mingw4.9.2版本是支持C++11的,如果你用的是老掉牙的rhel5系统,则需要升级编译器了,因为C++11要在GCC 4.5以上的版本中才会支持。

首先我们定义一个类:FunctionTransfer(函数大挪移),这个类继承自QObject,并使用Q_OBJECT标签来使用信号槽机制。代码中的“std::tr1::function<void()>”就是C++标准库中大名鼎鼎的函数对象。

class FunctionTransfer : public QObject

{

    Q_OBJECT

public:

    ///@brief 构造函数

    explicit FunctionTransfer(QObject *parent = 0);

public:

    ///@brief 制定函数f在main中执行

static void execinmain(std::tr1::function<void()> f);

signals:

    ///@brief 在别的线程有函数对象传来

    void comming(std::tr1::function<void()> f);

public slots:

    ///@brief 执行函数对象

    void exec(std::tr1::function<void()> f);

};

然后是源文件:

//在全局数据区实例化一个FunctionTransfer的实例,该实例所在的县城就是主线程。

FunctionTransfer main_thread_forward;
void FunctionTransfer::execinmain(std::tr1::function<void()> f)
{
    main_thread_forward.exec(f);
}
 
FunctionTransfer::FunctionTransfer(QObject *parent) :
    QObject(parent)
{
    connect(this,SIGNAL(comming(std::tr1::function<void()>)),this,SLOT(exec(std::tr1::function<void()>)),Qt::BlockingQueuedConnection);
}
 
 
void FunctionTransfer::exec(std::tr1::function<void()> f)
{
    if(Gt::isMainThread())
    {
        f();
    }
    else
    {
        emit this->comming(f);
    }
}

非常简单的逻辑,如果在主线程就执行,如果不是在主线程就发给主线程,主线程接到之后就执行。

类有了,接下来考虑实用的场合,比如有一个类 A,A有个方法f不能再后台执行,需要跑到前台,怎么办呢,上代码:

作为参数的lamda表达式捕获了类A的this指针,然后转换为C++的函数对象,然后跑到前台去执行了,执行完成后才会返回,是不是灰常简洁。

FunctionTransfer::execinmain([this](){this->f();});

http://my.oschina.net/fanhuazi/blog/737224

原文地址:https://www.cnblogs.com/findumars/p/5804430.html