c++ - 如何始终在 QDoubleSpinbox 中显示符号(+ 或 -)?

标签 c++ qt qt5 qdoublespinbox

如果 QDoubleSpinbox 中的值为正数,则不显示任何符号。

enter image description here

如果该值改为负数,它会自动添加“-”号。

enter image description here

如果前缀强制为“+”,则正数将带符号显示

doubleSB->setPrefix("+");

enter image description here

但是“+”会留在那里,当设置的值为负数时不会自动去掉

enter image description here

有没有办法始终显示正确的符号?

  • 如果值为正则打“+”
  • 如果值为负则用“-”表示(就像默认情况下一样)

最佳答案

一个可能的解决方案是覆盖 textFromValue()方法并在必要时添加该字符:

#include <QApplication>
#include <QDoubleSpinBox>

class DoubleSpinBox: public QDoubleSpinBox
{
public:
    using QDoubleSpinBox::QDoubleSpinBox;
    QString textFromValue(double value) const override
    {
        QString text = QDoubleSpinBox::textFromValue(value);
        if(value > 0)
            text.prepend(QChar('+'));
        return text;
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    DoubleSpinBox w;
    w.setMinimum(-100);
    w.setSuffix("%");
    w.show();

    return a.exec();
}

关于c++ - 如何始终在 QDoubleSpinbox 中显示符号(+ 或 -)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53106708/

相关文章:

c++ - 指针保护和性能

python - 在设定的时间间隔内调用 QCoreApplications.processEvents() 安全吗?

qt - 安装 QWT 库时出错

mysql - MySQL select 语句的 QSlQuery 失败

qt - 如何使用 OpenSSL 支持构建 Qt5

c++ - 加载 TensorFlow 模型以使用 C++ 操作音频流

c++ - 将 char[] 转换为 char*

c++ - 如何在用Boost MSM编写的状态机中直接达到任何状态

qt - Qt 5 中的 OpenGL 与 QOpenGL/QtOpenGL : differences and limitations?

c++ - 调用QQmlPropertyMap子进程的子进程?