绘画QWidget外部GUI线程的问题 [英] Painting Issue on QWidget outsite GUI thread

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

问题描述

我正在开发一个应用程序,其中我想从远程主机连续接收图像,并在我的屏幕上显示它们。为此我遵循给定的策略
1)我有一个主要的QWidget对象包含QImage它(工作正常)
2)从远程主机接收的图像绘在QImage对象,这项工作使用QPainter在工作线程中完成。 (工作正常)
3)但问题是图像不更新QWidget,除非我调整窗口小部件的大小,因为重绘事件被调用QWidget ...现在如果我从工作线程重新绘制QWidget它会给出错误QPixmap:在GUI线程之外使用pixmaps不安全和应用程序崩溃。

I am developing an appliation in which I want to continuously receive images from remote host and display them on my screen. for this I am following the given strategy 1) I have a main QWidget object which contains the QImage on it (works fine) 2) Images received from remote host are painted on QImage object, this work is done in a worker thread using QPainter. (works fine) 3) but the problem is that the image is not updated on QWidget, unless I resize the widget, because the repaint event is called for QWidget... Now if i repaint the QWidget from the worker thread it gives error "QPixmap: It is not safe to use pixmaps outside the GUI thread".. and application crashes.

有关这方面的任何帮助吗?

Any help regarding this?

推荐答案

使用 QueuedConnection

发出工作线程的信号

Emit a signal from the worker thread with a QueuedConnection
or post an update event (QPaintEvent) to the widget from the worker thread.

//--------------Send Queued signal---------------------
class WorkerThread : public QThread
{
    //...
signals:
    void updateImage();

protected:
    void run()
    {
        // construct QImage
        //...
        emit updateImage();
    }
    //...
};

//...
widgetThatPaintsImage->connect(
    workerThread, 
    SIGNAL(updateImage()), 
    SLOT(update()),
    Qt::QueuedConnection);
//...

//--------------postEvent Example-----------------------
class WorkerThread : public QThread
{
    //...
protected:
    void run()
    {
        //construct image
        if(widgetThatPaintsImage)
        {
            QCoreApplication::postEvent(
                widgetThatPaintsImage, 
                new QPaintEvent(widgetThatPaintsImage->rect()));
        }
        //... 
    }

private:
    QPointer<QWidget> widgetThatPaintsImage;
};

不要忘记同步对图片的访问。

作为同步的替代方法,您还可以将图像发送到gui主题,例如 Mandelbrot示例

Don't forget to synchronize the access to the image.
As an alternative to the synchronization, you could also send the image to the gui thread, like in the Mandelbrot Example.

这篇关于绘画QWidget外部GUI线程的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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