在我的一个项目中,我有一系列QLineEdit
小部件,它们应该接受双数,它们位于一定范围内。由于某些原因我不能使用QDoubleSpinBox
.
现在我QDoubleValidator
用来检查我的号码是否在给定的范围内。不幸的是,只有在给editingFinished
时才会发出信号。QValidator
QValidator::Acceptable
现在假设,我可能有一系列这样的QLineEdit
小部件。在一个中,我输入了一个错误的数字,然后我将焦点切换到另一个小部件。用户在QLineEdit
.
相反,我想要的行为是将焦点设置到包含错误输入并发出警告的小部件上。
由于某些原因,我未能实现此功能。即使在我查阅了 Qt 文档之后。
这是我的完整代码。
ValidatedDoubleEditorWidget.h
#pragma once
#include <QWidget>
namespace Ui {
class validatedDoubleEditorWidget;
}
class QDoubleValidator;
class ValidatedDoubleEditorWidget : public QWidget {
Q_OBJECT
public:
ValidatedDoubleEditorWidget(double min, double max, double value);
double getValue() const;
void setValue(const double value);
private slots:
void on_lineEdit_editingFinished();
protected:
virtual void focusOutEvent(QFocusEvent *event) override;
virtual void focusInEvent(QFocusEvent *event) override;
private:
Ui::validatedDoubleEditorWidget* mWidget = nullptr;
double mValue = 0.;
double mMin = 0.;
double mMax = 0.;
QDoubleValidator* mValidator = nullptr;
};
ValidatedDoubleEditorWidget.cpp
#include "ValidatedDoubleEditorWidget.h"
#include <QDoubleValidator>
#include <QMessageBox>
#include <QDebug>
#include "ui_ValidatedDoubleEditorWidget.h"
ValidatedDoubleEditorWidget::ValidatedDoubleEditorWidget(double min, double max, double value)
{
mWidget = new Ui::validatedDoubleEditorWidget;
mWidget->setupUi(this);
mValue = value;
mWidget->lineEdit->setText(QString("%1").arg(value));
mValidator = new QDoubleValidator(min, max, 20, this);
mWidget->lineEdit->setValidator(mValidator);
setFocusProxy(mWidget->lineEdit);
setFocusPolicy(Qt::StrongFocus);
}
double ValidatedDoubleEditorWidget::getValue() const
{
return mValue;
}
void ValidatedDoubleEditorWidget::setValue(const double value)
{
mValue = value;
mWidget->lineEdit->setText(QString("%1").arg(value));
}
void ValidatedDoubleEditorWidget::on_lineEdit_editingFinished()
{
QString text = mWidget->lineEdit->text();
qDebug() << "Editing finished";
bool ok;
double value = text.toDouble(&ok);
if (!ok) {
//
}
else {
mValue = value;
}
}
void ValidatedDoubleEditorWidget::focusOutEvent(QFocusEvent *event)
{
qDebug() << "OutFocus";
QString text = mWidget->lineEdit->text();
int i;
auto state=mValidator->validate(text, i);
if (state != QValidator::Acceptable) {
QMessageBox::warning(this, tr("Invalid Input!"), tr("Please check your input."), QMessageBox::Ok);
mWidget->lineEdit->setText(QString("%1").arg(mValue));
mWidget->lineEdit->setFocus();
}
}
void ValidatedDoubleEditorWidget::focusInEvent(QFocusEvent *event)
{
qDebug() << "InFocus";
}
测试运行程序.cpp
#include <QApplication>
#include <QMap>
#include <QFrame>
#include <QHBoxLayout>
#include "ValidatedDoubleEditorWidget.h"
int main(int argc, char** args) {
QApplication app(argc, args);
QFrame frame;
frame.setLayout(new QHBoxLayout);
frame.layout()->addWidget(new ValidatedDoubleEditorWidget(-1., 4., 1.));
frame.layout()->addWidget(new ValidatedDoubleEditorWidget(-2., 4., 5.));
frame.show();
app.exec();
return 0;
}