How to show on QML (Qt) from SQLite BLOB data as i

2019-02-27 07:50发布

My code is like below.

Name - as TEXT field,

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

Selecting data

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

Binding in QML

ListView {
    id: someListView
    model: SqlContactModel {}
    delegate: ItemDelegate {
        text: Name
        Image {
            id: Photo
            source: ???
        }
    }
}

How to show on QML (Qt) from SQLite BLOB data as image?

标签: qt sqlite qml blob
1条回答
SAY GOODBYE
2楼-- · 2019-02-27 08:05

You have three options:

  1. let the model hand out some ID and use that with a QQuickImageProvider
  2. let the model hand out a QImage and write a custom item that can display that
  3. let the model hand out the image data as a data URI

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

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

查看更多
登录 后发表回答