QT4如何使用静态字段?
我试图在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
静态字段就像类中的方法。首先您需要声明它们,然后需要定义它们的初始值。
对于 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.