我正在QT Creator上構建一個C++ GUI應用程序。 我將位置更改爲葡萄牙語/巴西,現在只有逗號是小數點分隔符。C++ - Qt Creator - /如何在QDoubleSpinBox上將DOT和COMMA作爲小數點分隔符?
我需要QDoubleSpinBox得到小數點分隔符點和逗號。 官方逗號是葡萄牙語的分隔符,但某些鍵盤只在數字部分中有點。
請幫幫忙,
我正在QT Creator上構建一個C++ GUI應用程序。 我將位置更改爲葡萄牙語/巴西,現在只有逗號是小數點分隔符。C++ - Qt Creator - /如何在QDoubleSpinBox上將DOT和COMMA作爲小數點分隔符?
我需要QDoubleSpinBox得到小數點分隔符點和逗號。 官方逗號是葡萄牙語的分隔符,但某些鍵盤只在數字部分中有點。
請幫幫忙,
你也可以繼承QDoubleSpinBox
和重新實現validate
方法同時接受點和逗號作爲小數點分隔符。我認爲只要在輸入是一個句點並允許它被接受時(只要在字符串中沒有其他句點或逗號),就可以添加一個特殊的檢查,但另外調用基類實現。我還沒有編譯或測試,但我認爲這是非常接近:
MyDoubleSpinBox::validate (QString &input, int &pos)
{
if (input == ".")
{
return (text().contains (".") || text().contains (",")) ? QValidator::Invalid : QValidator::Acceptable;
}
return QDoubleSpinBox::validate (input, pos);
}
子類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);
}
您的解決方案不起作用!首先,因爲你的三元論是錯誤的(你應該改變無效和可接受的)。其次,您的輸入是整個文本,所以只有在您輸入if內時,纔是在spinbox內單詞的開頭輸入一個點。我將建議不同的解決方案,但我等待,因爲我更喜歡先測試它。 – basslo
當然歡迎您提供更正的答案。對於我沒有編寫或測試過這個答案的答案,我很抱歉,因爲答案不完全準確,但我認爲它非常接近。 – goug