问题描述
我的代码如下.
名称-作为TEXT字段,
Name - as TEXT field,
照片-作为BLOB数据
Photo - as BLOB data
class SqlQueryModel: public QSqlQueryModel
{
Q_OBJECT
QHash<int,QByteArray> *hash;
public:
explicit SqlQueryModel(QObject * parent) : QSqlQueryModel(parent)
{
hash = new QHash<int,QByteArray>;
hash->insert(Qt::UserRole, QByteArray("Name"));
hash->insert(Qt::UserRole + 1, QByteArray("Photo"));
}
inline RoleNameHash roleNames() const { return *hash; }
};
选择数据
view = new QQuickView();
QSqlQueryModel *someSqlModel = new SqlQueryModel(this);
someSqlModel->setQuery("SELECT Name, Photo FROM some_table");
QQmlContext *context = view->rootContext();
context->setContextProperty("someSqlModel", someSqlModel);
view->setSource(QUrl("qrc:///MainView.qml"));
view->show();
在QML中绑定
ListView {
id: someListView
model: SqlContactModel {}
delegate: ItemDelegate {
text: Name
Image {
id: Photo
source: ???
}
}
}
如何从SQLite BLOB数据中以图像形式显示在QML(Qt)上?
How to show on QML (Qt) from SQLite BLOB data as image?
推荐答案
您有三个选择:
- 让模型分发一些ID并与
QQuickImageProvider
一起使用 - 让模型分发
QImage
并编写一个可以显示该内容的自定义项 - 让模型以数据URI 的形式分发图像数据.
- let the model hand out some ID and use that with a
QQuickImageProvider
- let the model hand out a
QImage
and write a custom item that can display that - let the model hand out the image data as a data URI
对于(2),最简单的解决方案是QQuickPaintedItem
派生类,类似这样
For (2) the simplest solution is a QQuickPaintedItem
derived class, something like this
class QImageItem : public QQuickPaintedItem
{
Q_OBJECT
Q_PROPERTY(QImage image READ image WRITE setImage NOTIFY imageChanged)
public:
explicit QImageItem(QQuickItem *parent = Q_NULLPTR) : QQuickPaintedItem(parent) {}
QImage image() const { return m_image; }
void setImage(const QImage &image);
void paint(QPainter *painter) Q_DECL_OVERRIDE;
private:
QImage m_image;
};
void QImageItem::setImage(const QImage &image)
{
m_image = image;
emit imageChanged();
update();
setImplicitWidth(m_image.width());
setImplicitHeight(m_image.height());
}
void QImageItem::paint(QPainter *painter)
{
if (m_image.isNull()) return;
painter.drawImage(m_image.scaled(width(), height()));
}
通常在qmlRegisterType<QImageItem>("SomeModuleName", 1, 0, "SomeTypeName")
和QML import SomeModuleName 1.0
中进行注册,并使用SomeTypeName
而不是Image
,并且模型返回的QImage
绑定到项目的image
属性
Register as usual with qmlRegisterType<QImageItem>("SomeModuleName", 1, 0, "SomeTypeName")
and in QML import SomeModuleName 1.0
and use SomeTypeName
in instead of Image
, with the QImage
returned by the model bound to the item's image
property
这篇关于如何从SQLite BLOB数据以图像形式显示在QML(Qt)上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!