Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a QImage object to QML's Image element from C++ side multiple times?

I am have a QImage object in my Qt app on the C++ side of code.

Image {
   id: my_image
   source: ""
}

I have the QML Connections element in which I am getting a QImage sent

Connections {
    target: qimage_supplier
    onNewQImage: {
        recalled_media_image.source = new_qimage_supplied
    }
}

Question:
Is it possible to set a QImage object to the source of a Image QML item? Doing above way where new_qimage_supplied is actually a QImage sent from C++ side, it complains the following:

Error: Cannot assign QImage to QUrl

How can I set a QImage object to Image QML element?

like image 630
TheWaterProgrammer Avatar asked Dec 11 '25 15:12

TheWaterProgrammer


1 Answers

This is a quick and dirty example (not for copy and paste!)

// in main.cpp (imports are missing)

class MyImageProvider: public QQuickImageProvider
{
    QImage m_image;
public:
    MyImageProvider(QImage img)
        : QQuickImageProvider(QQuickImageProvider::Image)
        , m_image(img)
    {}

    QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize) override {
        qDebug() << m_image;
        return m_image;
    }
};

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;   
    engine.addImageProvider("myimg", new MyImageProvider(QImage("C:/.../image.png")));
    engine.load(QUrl(QStringLiteral("main.qml")));

    return app.exec();
}

// in main.qml

ApplicationWindow {
    id: rootWin
    width: 800; height: 600; visible: true

    Image {
        source: "image://myimg/1"
    }
}

The source is:

image://registeredNameOfImageProvider/potentialId
like image 139
derM Avatar answered Dec 13 '25 10:12

derM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!