Display Image From URL in Qt 6

Display Image From URL in Qt 6

Qt is a powerful and versatile framework for developing cross-platform GUI applications with a rich set of features. One common task in many applications is displaying images sourced from URLs, and Qt provides convenient tools to achieve this. This tutorial explains how to display image from URL in Qt 6.

Provided code utilizes the Qt framework to create a simple application that downloads an image from a specified URL and displays it in a graphical user interface. The main function initializes the application and sets up the user interface components, such as a window, layout, and label.

A network request is initiated to retrieve the image from the given URL, and a connection is established between the request's completion signal and a lambda function. This function processes the response, loading the image data into a pixel map and displaying it on the label if there are no errors.

#include <QApplication>
#include <QLabel>
#include <QVBoxLayout>
#include <QNetworkReply>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QString imageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Google.png/640px-Google.png";

    auto *window = new QWidget();
    auto *layout = new QVBoxLayout(window);
    auto *label = new QLabel();
    layout->addWidget(label);

    QNetworkAccessManager networkManager;
    QNetworkReply *reply = networkManager.get(QNetworkRequest(QUrl(imageUrl)));

    QObject::connect(reply, &QNetworkReply::finished, [reply, label]() {
        if (reply->error() == QNetworkReply::NoError) {
            QPixmap pixmap;
            pixmap.loadFromData(reply->readAll());
            label->setPixmap(pixmap);
        } else {
            qDebug() << reply->error();
        }
        reply->deleteLater();
    });

    window->show();

    return QApplication::exec();
}

Leave a Comment

Cancel reply

Your email address will not be published.