SEGFAULT in paintEvent() and drawImage() [SOLVED]



  • Hi, i have created a widget that inherits from QWidget and reimplements paintEvent. The only purpose of this widget is to show a QImage as faster as possible. This is the code;

    @
    void ImageDisplay::paintEvent(QPaintEvent *event)
    {
    QWidget::paintEvent(event);

    QImage image = this->m_image; 
    
    QSize size = image.size();
    size.scale(this->size(), Qt::KeepAspectRatio);
    QRect rect(QPoint(), size);
    rect.moveCenter(this->rect().center());
    
    QPainter painter(this);
    
    painter.drawImage(rect,
                      image,
                      image.rect());
    

    }

    void ImageDisplay::setImage(const QImage &image)
    {
    this->m_image = image;

    this->update();
    

    }
    @

    But, it seams to cause a SEGFAULT when calling setImage in certain cases, specially when calling from inside a slot .
    When i debugg it with GDB, it give me the error in this line:

    @
    painter.drawImage(rect,
    image,
    image.rect());
    @

    But all parameters in rect and image are correct.
    When I change the line from:

    @ QImage image = this->m_image; @

    to (for example):

    @ QImage image = QImage("whatever.jpg"); @

    or when i comment the line:

    @ this->m_image = image; @

    It doesn't crashes.
    If i replace:

    @ this->update(); @

    with:

    @ this->repaint(); @

    In certain conditions it crashes, and in other works.

    So, I'm very confused, and no idea on how to solve this, ¿any ideas please?



  • Ok, based in "this":https://qt-project.org/doc/qt-4.8/qimage.html#QImage-6:

    bq. The buffer must remain valid throughout the life of the QImage. The image does not delete the buffer at destruction.

    I has been deleting the QImage pixel buffer before rendering it with drawImage().
    A quick solution could be (not the best way), change the line:

    @
    void ImageDisplay::setImage(const QImage &image)
    {
    this->m_image = image;

    this->update();
    

    }
    @

    to:

    @
    void ImageDisplay::setImage(const QImage &image)
    {
    this->m_image = image.copy();

    this->update();
    

    }
    @


Log in to reply
 

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