在QWidget外部GUI线程上绘制问题

Muh*_*mar 3 c++ linux qt qwidget qimage

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

对此有何帮助?

Tim*_*imW 9

从工作线程发出一个信号,发出QueuedConnection
更新事件(QPaintEvent)或从工作线程发送到窗口小部件.

//--------------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;
};
Run Code Online (Sandbox Code Playgroud)

不要忘记同步对图像的访问.
作为同步的替代方法,您还可以将图像发送到gui线程,就像在Mandelbrot示例中一样.