开发者

Qt C++: Static list of font families

开发者 https://www.devze.com 2023-03-02 09:25 出处:网络
This may be more a general C++ programming question than Qt specific.The problem I\'m having is with static members and 开发者_Go百科initializing them.

This may be more a general C++ programming question than Qt specific. The problem I'm having is with static members and 开发者_Go百科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!


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;
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消