2017-03-01 52 views

回答

0

你也可以繼承QDoubleSpinBox和重新實現validate方法同時接受點和逗號作爲小數點分隔符。我認爲只要在輸入是一個句點並允許它被接受時(只要在字符串中沒有其他句點或逗號),就可以添加一個特殊的檢查,但另外調用基類實現。我還沒有編譯或測試,但我認爲這是非常接近:

MyDoubleSpinBox::validate (QString &input, int &pos) 
{ 
    if (input == ".") 
     { 
     return (text().contains (".") || text().contains (",")) ? QValidator::Invalid : QValidator::Acceptable; 
     } 

    return QDoubleSpinBox::validate (input, pos); 
} 
+0

您的解決方案不起作用!首先,因爲你的三元論是錯誤的(你應該改變無效和可接受的)。其次,您的輸入是整個文本,所以只有在您輸入if內時,纔是在spinbox內單詞的開頭輸入一個點。我將建議不同的解決方案,但我等待,因爲我更喜歡先測試它。 – basslo

+0

當然歡迎您提供更正的答案。對於我沒有編寫或測試過這個答案的答案,我很抱歉,因爲答案不完全準確,但我認爲它非常接近。 – goug

0

子類QDoubleSpinBox並重新實現虛方法驗證

完整的解決方案在這裏:

customSpinBox.h

#ifndef WIDGET_H 
#define WIDGET_H 

#include <QWidget> 
#include <QRegExpValidator> 
#include <QDoubleSpinBox> 



class CustomSpinBox : public QDoubleSpinBox { 
    Q_OBJECT 

public: 
    explicit CustomSpinBox(QWidget* parent =0); 
    virtual QValidator::State validate(QString & text, int & pos) const; 

private: 
    QRegExpValidator* validator; 

}; 
#endif // WIDGET_H 

customSpinBox.cpp

CustomSpinBox::CustomSpinBox(QWidget *parent):QDoubleSpinBox(parent), 
    validator(new QRegExpValidator(this)) 
{ 
    validator->setRegExp(QRegExp("\\d{1,}(?:[,.]{1})\\d*")); 
} 

QValidator::State CustomSpinBox::validate(QString &text, int &pos) const 
{ 
    return validator->validate(text,pos); 
} 
相關問題