How to declare and instantiate a variable in Qt?
At first I want to apologize for this stupid question, but I'm fairly new to Q开发者_如何学Pythont, so forgive me ;)
I'm drawing QPixmaps
. But for performance issues I only want to load my QPixmaps
once to use them over and over again. At the moment I'm loading them always when update is called, but it should be possible to load them only once in the constructor. How would the .h
file and the declaration of the QPixmap
variables look in this case? Couldn't figure it out so far.
Qt is a C++ library, so you just write c++ code:
Header:
class foo : public QWidget {
public:
foo(QWidget *parent = 0);
private:
QPixMap *bar;
};
Source:
foo::foo(QWidget *parent) : QWidget(parent) {
bar = new QPixMap("bar.png");
// Some error checking...
}
You might not need to optimize the image loading: if you load them by passing a filename parameter to the constructor of QPixmap
or to QPixmap::load
, they are automatically cached in QPixmapCache
as mentioned here.
And if you really want to keep a QPixmap
as a member in your class, you shouldn't use a pointer because, basically:
- the
QPixmap
objects are already smart pointers, like all Qt "implicitly shared types" from that list and, - raw pointers are evil, because, they can be invalid and they need to be deleted manually.
精彩评论