Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top