显示来自 sqlite 错误的图像
我已经在 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 © 2011."
"<p>Message Box To Check For "
" Errors "
));
}
ui.imageLabel->setPixmap( QPixmap::fromImage(image));
}
项目编译没有任何错误,但图像不会显示。
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 © 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议在您的代码中添加一些错误检查,以缩小错误发生的位置。
例如,
QImageReader::read()
表示如果无法读取图像,则生成的图像为空,并且它告诉您如何找出错误所在。
因此,在调用
reader.read()
后,请检查image.isNull()
。早些时候,检查 array.size() 以确保您确实从数据库中获得了值。
检查 buffer.open( QIODevice::ReadOnly ) 返回的结果 - 文档说如果调用失败它将返回 false。
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()
, checkimage.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 returnfalse
if the call failed.