我有一个QSpinbox
,我正在设置其范围:
QSpinBox *SpinBox = new QSpinBox;
SpinBox->setRange(0, 100);
但是,我可以手动输入一个未反映在我的插槽中的+
符号。
connect (SpinBox, SIGNAL (valueChanged (QString)), this,
SLOT (onSpinBoxChanged (QString)));
我也尝试用int
替换QString
。但+
不会反映在插槽中。
如何限制进入+
标志?
我已经参考了一些Qt和StackOverflow帖子/在旋转框中禁用行编辑的答案:
我试图使旋转框的行编辑ReadOnly
但我无法这样做,因为它是一个const
变量。
一些答案建议继承QSpinbox
类。
有没有其他方法可以限制+
符号或禁用QSpinbox
的行编辑本身?
如果您不想从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);
}