How to load an image from a file in Qt?

我与影子孤独终老i 提交于 2020-06-22 13:18:21

问题


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.


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/31522059/how-to-load-an-image-from-a-file-in-qt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!