C++;-Qt Creator-/如何在QDoubleSpinBox上使用点和逗号作为十进制分隔符? 我在QT创建者上构建了C++ GUI应用程序。 我将位置更改为葡萄牙语/巴西,现在只有逗号是小数分隔符
我需要QDoubleSpinBox作为小数点分隔符和逗号。 葡萄牙语中逗号是分隔符,但有些键盘的数字部分只有点C++;-Qt Creator-/如何在QDoubleSpinBox上使用点和逗号作为十进制分隔符? 我在QT创建者上构建了C++ GUI应用程序。 我将位置更改为葡萄牙语/巴西,现在只有逗号是小数分隔符,c++,qt,C++,Qt,我需要QDoubleSpinBox作为小数点分隔符和逗号。 葡萄牙语中逗号是分隔符,但有些键盘的数字部分只有点 请提供帮助,您可以将QDoubleSpinBox子类化,并重新实现验证方法以接受点和逗号作为十进制分隔符。我认为,当输入是句点时,只需添加一个特殊检查即可,并允许接受它(前提是字符串中没有其他句点或逗号),否则调用基类实现。我还没有编译或测试过这个,但我认为这非常接近: MyDoubleSpinBox::validate (QString &input, int &po
请提供帮助,您可以将
QDoubleSpinBox
子类化,并重新实现验证
方法以接受点和逗号作为十进制分隔符。我认为,当输入是句点时,只需添加一个特殊检查即可,并允许接受它(前提是字符串中没有其他句点或逗号),否则调用基类实现。我还没有编译或测试过这个,但我认为这非常接近:
MyDoubleSpinBox::validate (QString &input, int &pos)
{
if (input == ".")
{
return (text ().contains (".") || text ().contains (",")) ? QValidator::Invalid : QValidator::Acceptable;
}
return QDoubleSpinBox::validate (input, pos);
}
子类QDoubleSpinBox并重新实现虚拟方法validate 完整解决方案如下: 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
我试图将解决方案从basslo转换为Qt6.0,但它无法接受整数。下面的解决方案对我使用Qt6.0很好
#pragma once
#include <qtWidgets>
class CRelaxedDoubleSpinBox : public QDoubleSpinBox {
Q_OBJECT
public:
explicit CRelaxedDoubleSpinBox(QWidget* parent =0) : QDoubleSpinBox(parent)
{
}
virtual QValidator::State validate(QString & text, int & pos) const
{
QString s = QString(text).replace(".", ",");
return QDoubleSpinBox::validate(s,pos);
}
double valueFromText(const QString& text) const
{
QString s = QString(text).replace(",", ".");
return s.toDouble();
}
};
#pragma一次
#包括
CRelaxedDoubleSpinBox类:公共QDoubleSpinBox{
Q_对象
公众:
显式CRelaxedDoubleSpinBox(QWidget*parent=0):QDoubleSpinBox(parent)
{
}
虚拟QValidator::状态验证(QString&text,int&pos)常量
{
QString s=QString(文本)。替换(“.”,“,”);
返回QDoubleSpinBox::验证(s、pos);
}
双值fromtext(常量QString&text)常量
{
QString s=QString(文本)。替换(“,”,”);
返回s.toDouble();
}
};
您的解决方案不起作用!首先是因为你的三元数是错误的(你应该切换无效和可接受)。其次,您的输入是整个文本,因此您在if中输入的唯一时间是在spinbox中输入单词开头的一个点。我本来打算以不同的方式提出相同的解决方案,但我等待是因为我更喜欢先测试它。当然欢迎您提供正确的答案。我很抱歉回答得不完全准确,我说我没有编译或测试这个,但我认为它非常接近。
#pragma once
#include <qtWidgets>
class CRelaxedDoubleSpinBox : public QDoubleSpinBox {
Q_OBJECT
public:
explicit CRelaxedDoubleSpinBox(QWidget* parent =0) : QDoubleSpinBox(parent)
{
}
virtual QValidator::State validate(QString & text, int & pos) const
{
QString s = QString(text).replace(".", ",");
return QDoubleSpinBox::validate(s,pos);
}
double valueFromText(const QString& text) const
{
QString s = QString(text).replace(",", ".");
return s.toDouble();
}
};