views:

424

answers:

2

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?

+5  A: 

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;
};

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.

TimW
can you please send me some code snippet which can help .
Ummar
A: 

GUI operations outside the main thread are not allowed in Qt. All GUI operations need to be done in the main thread, the thread where QApplication lives. Any GUI operation in another thread gives unpredictable results, i.e. crashes.

erelender