Qt QSpinbox设置范围后接受'+'符号

时间:2018-09-21 04:16:25

标签: c++ qt qt5 qspinbox

我有一个QSpinbox我要设置的范围:

QSpinBox *SpinBox = new QSpinBox;
SpinBox->setRange(0, 100);

但是,我可以手动输入一个+符号,该符号不会反映在我的广告位中。

connect (SpinBox, SIGNAL (valueChanged (QString)), this,
            SLOT (onSpinBoxChanged (QString)));

我也尝试用QString替换int。但是+不会反映在广告位中。

如何限制输入+符号?

我已经提到了一些Qt和StackOverflow帖子/答案,它们禁用了Spinbox中的行编辑:

我试图对Spinbox进行行编辑ReadOnly,但由于它是const变量,所以我无法这样做。

一些答案​​建议继承QSpinbox类。

是否有其他方法来限制+符号或禁用QSpinbox的行编辑本身?

1 个答案:

答案 0 :(得分:3)

如果不想从QSpinBox类继承,可能的解决方案是使用eventFilter,在下面的代码中,我显示一个示例:

#include <QApplication>
#include <QSpinBox>
#include <QLineEdit>
#include <QKeyEvent>

class PlusRemoveHelper: public QObject{
public:
    using QObject::QObject;
    void addWidget(QWidget *widget){
        if(widget){
            widgets.append(widget);
            widget->installEventFilter(this);
        }
    }
public:
    bool eventFilter(QObject *watched, QEvent *event) override
    {
        if(std::find(widgets.begin(), widgets.end(), watched) != widgets.end()
                && event->type() == QEvent::KeyPress){
            QKeyEvent *keyevent = static_cast<QKeyEvent *>(event);
            if(keyevent->text() == "+")
                return true;
        }
        return  QObject::eventFilter(watched, event);
    }
private:
    QWidgetList widgets;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QSpinBox w;
    w.setRange(0, 100);
    PlusRemoveHelper helper;
    helper.addWidget(&w);
    w.show();

    return a.exec();
}

如果您位于小部件内,则可以实现相同的逻辑:

*。h

...
class QSpinBox;

class SomeClass: public SuperClass
{
...
public:
    bool eventFilter(QObject *watched, QEvent *event);
private:
    ...
    QSpinBox *SpinBox
};

*。cpp

SomeClass::SomeClass(...):
  SuperClass(..)
{
    SpinBox = new QSpinBox;
    SpinBox->setRange(0, 100);
    SpinBox->installEventFilter(this):
}


bool SomeClass::eventFilter(QObject *watched, QEvent *event){
    if(watched == SpinBox && event->type() == QEvent::KeyPress){
        QKeyEvent *keyevent = static_cast<QKeyEvent *>(event);
        if(keyevent->text() == "+")
            return true;
    }
    return  SomeClass::eventFilter(watched, event);
}