[Qt-interest] static struct of QIcons?

K. Frank kfrank29.c at gmail.com
Mon Mar 29 20:59:32 CEST 2010


To All -

I have a suggestion -- that doesn't seem to work -- and a question.

On Mon, Mar 29, 2010 at 10:57 AM, Kārlis Repsons <k at 11.lv> wrote:
> On Monday 29 March 2010 12:29:39 Kārlis Repsons wrote:
>> Is that possible to put all icons of resource file into a static struct?
>>
>> Similar to this:
>>
>>     static struct
>>     {
>>       QIcon minus(":/images/minus.png");
>>       QIcon plus(":/images/plus.png");
>>     } icons;
>>
>> The intent is to get a struct, which could provide references to icons...

Based on what I think the original poster is trying to accomplish, I put
together the following variation:

   struct MyIcons {
     MyIcons() : plus("plus.png"), minus("minus.png") {}
     const QIcon plus;
     const QIcon minus;
     const QIcon &getPlus() const { return plus; }
     const QIcon &getMinus() const { return minus; }
   };

   static MyIcons icons;

Unfortunately, this crashed at startup, for reasons I don't understand.  Could
someone explain what is wrong here?

If I get rid of "static MyIcons icons;", things (seem to) work fine.

   test_main::test_main (QWidget *parent) {
     setupUi (this);
     // ...
     MyIcons icons;     // <-- MyIcons instantiated -- just not static
     setWindowIcon (icons.getPlus());
     // ...
   }

That is, the MyIcons class seems to be working okay, but the app crashes when
I try to declare a static instance of it.

(By the way, if I replace "QIcon" in the MyIcons class with
"std::string", everything
works, that is, I can declare a static instance of MyIcons and get the
strings out
of it at run time.)

So, I am puzzled.  Either I am missing something important about how to use
"static" in c++, or the call to the QIcon constructor makes use of some Qt
machinery that hasn't yet been initialized when (the static) MyIcons is being
initialized.

Would anyone know what is going on here?

Thanks.

> You might see the solution in http://www.cplusplus.com/forum/general/21591, if
> you want to. Well, it seems, static is impossible...

(Yes, it's true that you can't initialize the member-variable QIcon's when you
declare the class, but you can do it in an inline constructor, which is almost
as concise.  So static ought to be possible -- even though I couldn't make
it work with QIcon's.)


K. Frank




More information about the Qt-interest-old mailing list