【问题标题】:displaying image from sqlite error显示来自 sqlite 错误的图像
【发布时间】:2011-10-02 18:34:44
【问题描述】:

我已经在 sqlite 中保存了一个图像,我正在尝试使用此代码检索它并在 QLabel 中显示它。

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

}

项目编译没有任何错误,但图像不会显示。

【问题讨论】:

    标签: qt qt4 qpixmap


    【解决方案1】:

    我建议在您的代码中添加一些错误检查,以缩小错误发生的范围。

    例如,QImageReader::read() 的文档说如果无法读取图像,则生成的图像为空,它会告诉您如何找出错误所在。

    所以在您致电reader.read() 后,请检查image.isNull()

    之前,请检查 array.size() 以确保您确实从数据库中获得了返回值。

    检查buffer.open( QIODevice::ReadOnly ) 返回的结果 - 文档说如果调用失败,它将返回false

    【讨论】:

    • 我编辑包含 image.isNull() 并且似乎没有错误。
    • 这很奇怪。我刚刚用QLabel 编写了一个小程序,并调用label-&gt;setPixmap( QPixmap::fromImage(image)); 将图像放在标签上,就好了。 (我直接从您的代码中复制了 setPixmap 调用)
    • 连接中是否可以有 Qt::UniqueConnection(ui.tableView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), this, SLOT(getImage(QModelIndex,QModelIndex)) );?
    • 我不知道,恐怕。我知道图像和标签,但不知道数据库连接!当您发现您的图像不为空时,我建议关注图像本身是否实际有效,并包含您要从数据库中提取的实际图像。
    • 感谢您的精彩回答
    猜你喜欢
    • 2014-04-14
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 2013-08-07
    • 2015-08-18
    • 1970-01-01
    相关资源
    最近更新 更多