2016-02-29 783 views
0

我在我的项目中使用了大量的QDoubleSpinBoxes(使用Qt 4.8.0),并且对于所有这些项目,我希望获得与默认值不同的相同范围,单步大小,值等等。Qt4:如何为新实例更改QSpinBox的默认值(范围,值,单步大小)?

我想问一下:有没有办法改变这些默认值,这样QSpinBoxes的新实例将以新的默认值创建,这样我就不会每次都有变化?

简单地说,不是这样的:

QDoubleSpinBox *spin1 = new QDoubleSpinBox(this); 
spin1->setSingleStep(0.03); 
spin1->setDecimals(4); 
spin1->setRange(2.0, 35.0); 

QDoubleSpinBox *spin2 = new QDoubleSpinBox(this); 
spin2->setSingleStep(0.03); 
spin2->setDecimals(4); 
spin2->setRange(2.0, 35.0); 

... 

我想是这样的:

QDoubleSpinBox::setDefaultSingleStep(0.03); 
QDoubleSpinBox::setDefaultDecimals(4); 
QDoubleSpinBox::setDefaultRange(2.0, 35.0); 

QDoubleSpinBox *spin1 = new QDoubleSpinBox(this); 
QDoubleSpinBox *spin2 = new QDoubleSpinBox(this); 

有谁知道这是可能的,如果是,怎么样?

+2

也许最简单的方法是给QDoubleSpinBox子类并在新类的构造函数中设置新的默认值? – johngull

回答

3

您可以创建一个工厂,创建具有所需值的旋转框。

例如

class MySpinBoxFactory { 
public: 
    MySpinboxFactory(double singleStep, int decimals, double rangeMin, double rangeMax) 
    : m_singleStep(singleStep), m_decimals(decimals), m_rangeMin(rangeMin), m_rangeMax(rangeMax) {} 

    QDoubleSpinBox *createSpinBox(QWidget *parent = NULL) { 
     QDoubleSpinBox *ret = new QDoubleSpinBox(parent); 
     ret->setSingleStep(m_singleStep); 
     ret->setDecimals(m_decimals); 
     ret->setRange(m_rangeMin, m_rangeMax); 
     return ret; 
    } 
private: 
    double m_singleStep; 
    int m_decimals; 
    double m_rangeMin; 
    double m_rangeMax; 
} 

// ... 
MySpinboxFactory fac(0.03, 4, 2.0, 35.0); 
QDoubleSpinBox *spin1 = fac.createSpinBox(this); 
QDoubleSpinBox *spin2 = fac.createSpinBox(this); 

您还可以添加setters来更改值。有了这个,您可以使用单个工厂实例创建具有不同默认值的旋转箱。

MySpinboxFactory fac(0.03, 4, 2.0, 35.0); 
QDoubleSpinBox *spin1 = fac.createSpinBox(this); 
QDoubleSpinBox *spin2 = fac.createSpinBox(this); 

fac.setSingleStep(0.1); 
QDoubleSpinBox *spin3 = fac.createSpinBox(this); 
1

你应该让你自己的新类从QDoubleSpinBox派生。在你的类构造函数中,设置你想要的值。