简体   繁体   English

QT4如何使用静态字段?

[英]QT4 How to use static fields?

I am trying to use static fields in QT 我正在尝试在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 但是我总是收到“未定义的对MyLabel :: pix *'的引用”错误

How do i declare and use static fields of standart QT classes? 如何声明和使用标准QT类的静态字段?

PS I have no problems using int static fields, so i think my question is QT specific PS我使用int静态字段没有问题,所以我认为我的问题是QT特定的

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. 与QPixmaps有点不同。 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. QPixmap需要QApplication才能工作,因此您将无法使其静态化为变量,但是可以将其静态化为指针。 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. 在这两种情况下,它都必须为NULL,因为您仍然无法创建QPixmap。 Inside constructor of your class you may check if pointers are NULL, and if yes then you can initialize them with proper values. 在类的构造函数中,您可以检查指针是否为NULL,如果是,则可以使用适当的值对其进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM