在带有GCD的ObjC中,有一种在旋转事件循环的任何线程中执行lambda的方法.例如:
dispatch_sync(dispatch_get_main_queue(), ^{ /* do sth */ });
Run Code Online (Sandbox Code Playgroud)
要么:
dispatch_async(dispatch_get_main_queue(), ^{ /* do sth */ });
Run Code Online (Sandbox Code Playgroud)
它[]{ /* do sth */ }在主线程的队列中执行某些操作(相当于在C++中),阻塞或异步.
我怎么能在Qt中做同样的事情?
从我所读到的,我想解决方案将以某种方式向主线程的某个对象发送信号.但是什么对象呢?只是QApplication::instance()?(那是那时生活在主线程中的唯一对象.)什么信号?
从目前的答案和我目前的研究来看,似乎我需要一些虚拟对象来坐在主线程中,有一些插槽只是等待进入某些代码来执行.
所以,我决定使用子类QApplication来添加它.我目前的代码,但不起作用(但也许你可以帮忙):
#include <QApplication>
#include <QThread>
#include <QMetaMethod>
#include <functional>
#include <assert.h>
class App : public QApplication
{
Q_OBJECT
public:
App();
signals:
public slots:
void genericExec(std::function<void(void)> func) {
func();
}
private:
// cache this
QMetaMethod genericExec_method;
public:
void invokeGenericExec(std::function<void(void)> func, Qt::ConnectionType connType) {
if(!genericExec_method) {
QByteArray normalizedSignature = QMetaObject::normalizedSignature("genericExec(std::function<void(void)>)");
int …Run Code Online (Sandbox Code Playgroud) 有时我的应用程序在非GUI线程中执行的QWidget :: update()崩溃.
我正在开发一个应用程序,从远程主机接收视频帧并在QWidget上显示它们.
为此,我使用libVLC库给我一个解码图像.我在libVLC回调中接收图像,该图像在单独的libVLC线程中执行.在这个回调中,我正在尝试执行QWidget :: update()方法.有时应用程序崩溃,并且callstack在这个方法中的某个地方.这是我的回调代码:
//! Called when a video frame is ready to be displayed, according to the vlc clock.
//! \c picture is the return value from lockCB().
void VideoWidget::displayCB(void* picture)
{
QImage* image = reinterpret_cast<QImage*>(picture);
onScreenPixmapMutex_.lock();
onScreenPixmap_ = QImage(*image);
onScreenPixmap_.detach();
onScreenPixmapMutex_.unlock();
delete image;
update();
}
Run Code Online (Sandbox Code Playgroud)
我知道Qt中不允许主线程外的GUI操作.但根据文档QWidget :: update()只是在Qt返回主事件循环时调度一个paint事件进行处理,并且不会立即重新绘制.
问题是:QWidget :: update()是否适用"主线程外的GUI操作"规则?此操作是否属于"GUI操作"?
我使用Qt 4.7.3,在Windows 7和Linux上进行崩溃.