1

I am trying to get create a QIcon object from a website's favicon.ico file. Since this download doesn't necessarily happen on the GUI thread, I cannot use QPixmap, and so far I have had no luck figuring out how to convert from QImage to QIcon without using QPixmap, so I can't use something like QImageReader.

I have gotten the following code to work:

QUrl url("http://www.google.com/favicon.ico");
QNetworkRequest request(url);

QNetworkReply* pReply = manager.get(request);

// ... code to wait for the reply ...

QByteArray bytes(pReply->readAll());

QFile file("C:/favicon.ico");
file.open(QIODevice::WriteOnly);
file.write(bytes);
file.close();

QIcon icon("C:/favicon.ico");
return icon;

However, I want to avoid writing a temporary file. So I tried something like...

QBuffer buffer(&bytes);
buffer.open(QIODevice::ReadOnly);
QDataStream ds(&buffer);

QIcon icon;
ds >> icon;

But that doesn't work.

Does anyone have any suggestions?

Addy
  • 2,414
  • 1
  • 23
  • 43
  • How doesn't it work? Did you get runtime error? If so, what's the error. – Stephen Chu Nov 12 '12 at 00:08
  • No runtime errors. I use the returned QIcon in a QTreeView where I add a QStandardItem and pass the icon to the item I'm creating. As I mentioned, this works when I write the QByteArray to a temporary file and then use that file to initialize the QIcon. No icon shows up in the tree when I use the QDataStream method. – Addy Nov 12 '12 at 18:03

1 Answers1

2

QDataStream doesn't work because it's expecting a PNG image from the stream.

I wouldn't use the temp file approach either since it may still construct a QPixmap under the hood. In fact, QIcon is not guaranteed to be thread-safe and the use in non-GUI thread should be avoided.

I would just keep the byte array as is and pass it back to the GUI thread. Convert it into a QPixmap then a QIcon when you need to show it. It's not really so heavy a computation anyway.

Stephen Chu
  • 12,724
  • 1
  • 35
  • 46