QT4如何使用静态字段?

发布于 2024-09-28 16:55:57 字数 517 浏览 2 评论 0原文

我试图在 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

}

,但我总是收到“对 MyLabel::pix* 的未定义引用”错误

如何声明和使用标准 QT 类的静态字段?

PS 我使用 int 静态字段没有问题,所以我认为我的问题是 QT 特定的

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陈独秀 2024-10-05 16:55:57

静态字段就像类中的方法。首先您需要声明它们,然后需要定义它们的初始值。

对于 QPixmaps 来说有点不同。由于静态成员是在主入口点之前初始化的。 QPixmap 需要 QApplication 才能工作,因此您无法将其设置为静态变量,但您可以将其设置为静态指针。您还需要“定义”静态成员。通过定义,您可以声明它的初始值。在这两种情况下它都必须为 NULL,因为您仍然无法创建 QPixmap。在类的构造函数中,您可以检查指针是否为 NULL,如果是,则可以使用正确的值初始化它们。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文