0
votes

I've a problem with sending QImage to GUI-thread:

this is my code in child-thread:

QSize size = ui->label_2->size();
size=ui->label_2->size();
QImage pic(size.width(),size.height(),QImage::Format_ARGB32_Premultiplied);
pic.fill(Qt::transparent);
QPainter painter(&pic);
for (unsigned int i=0; i < wayVector.size(); i++){
    double *x = new double[wayVector[i].refs.size()];
    double *y = new double[wayVector[i].refs.size()];
    for (unsigned int j=0; j<wayVector[i].refs.size(); j++){
        x[j]=nodeHash[wayVector[i].refs[j]].lon;
        y[j]=nodeHash[wayVector[i].refs[j]].lat;
    }
    for (unsigned int j=0; j<wayVector[i].refs.size()-1;j++){
        painter.setPen(Qt::green);
        painter.drawLine(size.width()*x[j]/(maxlon-minlon),
                         size.height()*maxlat/(maxlat-minlat)-size.height()*y[j]/(maxlat-minlat),
                         size.width()*x[j+1]/(maxlon-minlon),
                         size.height()*maxlat/(maxlat-minlat)-size.height()*y[j+1]/(maxlat-minlat));
    }
}
emit sendPixmap(pic);

This is signal/slot connection:

 connect(this,SIGNAL(sendPixmap(QImage)),this,SLOT(setImage(QImage)));

And this is definition of slot:

void MainWindow::setImage(QImage img){
    ui->label_2->setPixmap(QPixmap::fromImage(img));
}

But nothing happened, label clears and no image appears. What I'm doing wrong? Waiting for your help :(

1
Try running your code in a main thread first. Also, I'm not sure you are allowed to use QPainter in a not GUI thread. Try to send your picture before changing it. - Amartel
@Amartel but wayVector and nodeHash exists in another thread's stack how will I send them to main? Using slot/signal ? - tema
Yes, you could use signal/slot for that. - Amartel
Try using Qt::QueuedConnection as the connection type in the connect call for sending between threads. - TheDarkKnight
The approach in general should work. The connect looks wrong though, sender and receiver are both "this". To make it work, the sender QObject must live in the secondary thread creating the image and the receiver in the UI (main) thread. - Frank Osterfeld

1 Answers

0
votes

From the documentation:

When using QPainter on a QImage, the painting can be performed in another thread than the current GUI thread

So what you intend to do should work. Are you sure you have set up your thread correctly? Your usage of ui->label_2 looks very suspicious, do you have ui elements in your thread or do you access GUI elements from your thread? Perhaps you should show us more of your code.