简体   繁体   中英

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, eg "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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM