buck
buck

Reputation: 1532

Qt C++: Static list of font families

This may be more a general C++ programming question than Qt specific. The problem I'm having is with static members and initializing them.

I have a table model class which inherits QAbstractTableModel and I want each to have a list of all system font families using QFontDatabase::families(). I'm trying to make this list of families static so that it is only populated once. What is the best way to do this? I'm having trouble understanding how to initialize the list since it's static. Here is an example of what I mean:


class Model : public QAbstractTableModel
{
public:
    Model();
protected:
    static QStringList fontFamilies;
}

Model::Model() : QAbstractTableModel(0)
{
    fontFamilies = QFontDatabase().families();
}

I think I'm not supposed to initialize in the constructor (and I haven't actually tried the above code to see what the compiler would say), but I'm not sure how to approach this. I don't think I can do


QStringList Model::fontFamilies = QFontDatabase().families();

Thanks if you can provide any help!

Upvotes: 1

Views: 4386

Answers (2)

Stephen Chu
Stephen Chu

Reputation: 12832

Non-trivial initialization of static variables is typically problematic. The functions you call for the initialization may depend on resources that are not initialized yet at the time. And you have no control on the order of what static is initialized first.

Using constructor is not a bad idea. You just have to make sure you initialize the statics only once:

Model::Model() : QAbstractTableModel(0)
{
    if(fontFamilies.isEmpty())
        fontFamilies = QFontDatabase().families();
}

Or instead of a static member variable, use an access function with static local. The static local will be allocated and initialized only when the function is called. It will most likely be after Qt library initialization:

const QStringList & Model::fontFamilies()
{
    static QStringList fm = QFontDatabase().families();
    return fm;
}

Upvotes: 1

Kien Truong
Kien Truong

Reputation: 11381

Static data member must be define outside class.

class Model : public QAbstractTableModel
{
public:
   Model();
protected:
    static QStringList fontFamilies;
}
QStringList Model::fontFamilies = QFontDatabase().families();

This should do the trick

Upvotes: 1

Related Questions