PixMap loaded from thread to a table view causes crash

  • Basically my application is loading many images from a directory and display in a tableview.

    And loading in to table is doing from a thread, by calling it like

    QFuture<void> f3 = QtConcurrent::run(this,&faceTable::loadFaceTableViewAsync,index);

    and inside the function the pixmap loaded to model like,

    void faceTable::loadFaceTableViewAsync(int index){
            QString imgPath =dbImageList.at(r);
            QPixmap pix(imgPath);
                QPixmap pixmap = pix.scaled(cellWidth-6,cellHeight-6, Qt::KeepAspectRatio, Qt::SmoothTransformation);
                QStandardItem *item = new QStandardItem();
                item->setData(QVariant(pixmap), Qt::DecorationRole);

    And this causing crash some times, I have attached the link to screen shot and seems related to pixmap cache.

    What could be the reason.

  • Moderators

    QPixmaps are not safe to use outside ui thread. Take a look at QImage instead.
    Also models provided by Qt are not thread safe. Calling setItem from another thread is not synchronized in any way. If you want a thread safe model you need to subclass and provide synchronization yourself. Synchronizing every model method can have terrible performance consequences though.

    Usually this is done differently. Create and add item in main thread and schedule the thread to load image into some cache or store or whatever storage structure you wish. When the thread is done it should emit a signal indicating that the given image has loaded. Connect a slot to this signal that will in the main thread set the data from the storage place to the item (images are implicitly shared so this will be light operation).

  • @Chris-Kawa

    Thanks for the answer, I will use QImage instead QPixmap.

    and regarding the point, "models provided by Qt are not thread safe " does it cause any access violation and crash of app or the UI is not going to update after filling up the model, I already noticed that using model inside the thread, some times it requires some user interaction(scroll,click) to re-load the data to view.

  • Moderators

    It's not safe to use Qt's models in other threads. Imagine your thread is removing a row that is being queried for painting in the main thread, or that you set data that is being currently read. That's a textbook example of undefined behavior. It can result in harmlessly not painting something on your machine, crashing for some of your users and randomly formatting hard drives on full moon nights. Don't do it. Ever.

    If you want to have a thread safe model you need to subclass it and provide synchronization primitives (mutexes etc.) in all of the access methods. that's generally not a good idea either.

  • Ok now I understand. I will follow your suggestion. Thanks for pointing me this.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.