开发者

QT4 How to use static fields?

开发者 https://www.devze.com 2023-01-21 15:56 出处:网络
I am trying to use static fields in QT 开发者_StackOverflowclass MyLabel:public QLabel{ Q_OBJECT public:

I am trying to use static fields in QT

开发者_StackOverflowclass 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消