[SOLVED] Compare QIcons



  • In my application the icon on some QPushButton and the tabIcon is updated based on a choice in a QComboBox (because the meaning of the button/tab changes).

    When writing (unit)tests for the application, I'd like to check if the correct QIcon was set. They are constructed from a resource each time, so for me it would be sufficient to just know the resource passed to the constructor. That name is thrown away however it turns out.

    So, how then could I achieve this? My latest attempt was to write the QIcon into a QByteArray using a QDataStream, and then compare the resulting byte arrays:

    bool CompareQIcon(const QIcon& icon1, const QIcon& icon2)
    {
      QByteArray a1;
      QDataStream stream1(&a1, QIODevice::WriteOnly);
      stream1 << qicon1;
    
      QByteArray a2;
      QDataStream stream2(&a2, QIODevice::WriteOnly);
      stream2 << qicon2;
    
      return a1 == a2;
    }
    

    This didn't go well however. It resulted in some crash somewhere deep down the Qt library when calling the operator<<() for the first icon. I tried for some time to figure out why. My best guess is that I need to allocate memory for the byte array before writing to it, but then this approach won't work, as I don't know the size up front.

    So two questions: am I overlooking something obvious in the above snippet other than my own suspicion? If not, how could I still achieve my goal of comparing two QIcons?


  • Qt Champions 2016

    hi
    Never tried but saw this post once:
    So if icon can become pixmap ..

    Convert QPixmap to "QImage":QImage using method "toImage":http://qt-project.org/doc/qt-4.8/qpixmap.html#toImage and after that use "operator ==":http://qt-project.org/doc/qt-4.8/qimage.html#operator-eq-eq to compare.


  • Moderators

    Comparison of pixmap can be very expensive


  • Qt Champions 2016

    @jsulm
    Well for icons and in unit testing, I assume the cost its not so important if the unit test is to see if the corrent
    icon was choosen.
    But good to keep in mind never the less



  • @mrjj @jsulm Thanks you for your replies. As it turns out, the crash I mentioned was actually caused by a subtle, yet important bug in our test infrastructure: we have a special fixture that will instantiate and destruct the QApplication instance before respectively after each test case. We initiated the argc and argv parameters with variables local to the constructor. For some reason creating a QIcon causes Qt to access argv, in other words: a crash.

    Short story: both your suggestion, but also my original approach work perfectly!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.