Question

I have saved an image in sqlite and i am trying to retrieve it and displaying it in a QLabel using this code.

connect(ui.tableView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
                this, SLOT(getImage(QModelIndex,QModelIndex)));


void smith::getImage()
{
    .......
    QModelIndex index = ui.tableView->currentIndex();
    QString sqlQuery = QString("SELECT image FROM %1 WHERE id=:id").arg(tableName);
    query.prepare(sqlQuery);
    QSqlRecord recordz = tableModel->record(index.row());
    query.bindValue(":id", recordz.value("id").toInt());
    query.exec();
    tableModel->select();

    QByteArray array = query.value(0).toByteArray();
    QBuffer buffer(&array);
    buffer.open( QIODevice::ReadOnly );

    QImageReader reader(&buffer, "PNG");
    QImage image = reader.read();

if( image.isNull() )
{
    QMessageBox::about(this, tr("Image Is Null"),
                       tr("<h2>Image Error</h2>"
                          "<p>Copyright &copy; 2011."
                          "<p>Message Box To Check For  "
                          " Errors "
                          ));
}
    ui.imageLabel->setPixmap( QPixmap::fromImage(image));

}

The project compiles without any errors but the image won't show.

Was it helpful?

Solution

I'd suggest adding some error-checking to your code, to narrow down where the error occurs.

For example, the documentation for QImageReader::read() says that if the image can't be read, the resultant image is null, and it tells you how to find out what the error was.

So after your call to reader.read(), check image.isNull().

And earlier on, check array.size() to make sure that you really got a value back from the database.

And the check the result returned by buffer.open( QIODevice::ReadOnly ) - the docs say it will return false if the call failed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top