tags:

views:

68

answers:

1

I am trying to use static fields in QT

class MyLabel:public QLabel{
    Q_OBJECT
public:
  static QPixmap pix1;
  static QPixmap *pix2;
  static int WasInited;
  ...
};

int MyLabel::WasInited = 0;

MyLabel::MyLabel(){
  . . . 
  if (WasInited==0)  pix1.load("pic.png");   // Error
  if (WasInited==0)  pix2->load("pic.png");  // Error
  WasInited=1; // Here using static field is OK

}

But i always get "undefined reference to MyLabel::pix*' " error

How do i declare and use static fields of standart QT classes?

P.S. I have no problems using int static fields, so i think my question is QT specific

+2  A: 

static fields are like methods in a class. First you need to declare them, then you need to define their initial value.

With QPixmaps it's a little bit different. As static members are initialized before main entry point. QPixmap requires QApplication to work, so you won't be able to make it static as variable, you may however make it static as pointers. You need also to "define" a static member. By definining you declare it's initial value. In both cases it HAS to be NULL, because you still can't create QPixmap. Inside constructor of your class you may check if pointers are NULL, and if yes then you can initialize them with proper values.

Kamil Klimek
If you would like to edit your answer to include general information for initializing statics and the exceptional case for QPixmaps, I'll delete my answer so it's all in one place.
Arnold Spence