How to load an image from a file in Qt?

Generally, I've been searching for a while and could not find a serious answer. The problem is that I've a QString variable containing certain url, e.g. "C:/Users/Me/Desktop/image.png". How to open it and display the image in my application window? I know the problem might seem trivial, however I can't find a working solution.

Upvotes: 2

Views: 29520

Answers (2)

VP.
VP.

Reputation: 16765

Load the image by using QPixmap and then show it with QLabel:

QString url = R"(C:/Users/Me/Desktop/image.png)";
QPixmap img(url);
QLabel *label = new QLabel(this);
label->setPixmap(img);

ImageViewer example

Upvotes: 17

Universe.Earth.Human
Universe.Earth.Human

Reputation: 41

void LoadAvatar(const std::string &strAvatarUrl, QLabel &lable)
{ 
   QUrl url(QString().fromStdString(strAvatarUrl));
   QNetworkAccessManager manager;
   QEventLoop loop;

   QNetworkReply *reply = manager.get(QNetworkRequest(url));
   QObject::connect(reply, &QNetworkReply::finished, &loop, [&reply, &lable,&loop](){
    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray jpegData = reply->readAll();
        QPixmap pixmap;
        pixmap.loadFromData(jpegData);
        if (!pixmap.isNull())
        {
            lable.clear();
            lable.setPixmap(pixmap);
        }
    }
    loop.quit();
  });

  loop.exec();
}

Upvotes: 4

Related Questions