In a dialog, when the tab key is pressed, the focus changes to another widget. In Qt, is there any signal for when a widget loses its focus? Can I use it to check if the input is valid or not? If not, can I set the focus back and ask the user to re-input?
2 回答
没有信号,但如果您想知道小部件何时失去焦点,void QWidget::focusOutEvent(QFocusEvent* event)
请在小部件中覆盖并重新实现。每当您的小部件失去焦点时都会调用它。要将焦点放在小部件上,请使用QWidget::setFocus(Qt::FocusReason)
.
要验证 a QLineEdit
or中的输入,QComboBox
您可以子类QValidator
化并实现您自己的验证器,或使用现有子类之一,QIntValidator
、QDoubleValidator
或QRegExpValidator
。QLineEdit::setValidator(const QValidator*)
分别用和设置验证器QComboBox::setValidator(const QValidator*)
。
如果要验证模式对话框的内容,一种方法是QDialog::exec()
使用如下实现覆盖:
int MyDialog::exec() {
while (true) {
if (QDialog::exec() == QDialog::Rejected) {
return QDialog::Rejected;
}
if (validate()) {
return QDialog::Accepted;
}
}
}
bool MyDialog::validate() {
if (lineEdit->text().isEmpty()) {
QMessageBox::critical(this, "Invalid value", "The specified value is not valid");
lineEdit->setFocus();
lineEdit->selectAll();
return false;
}
return true;
}
除非成功验证对话框的内容,否则它将不允许用户使用 OK 按钮或任何其他具有 Accepted 角色的按钮关闭对话框。在这个例子中,我假设对话框有一个QLineEdit
命名lineEdit
,并且该validate
函数将确保其内容不为空。如果是,它会将焦点设置为QLineEdit
并再次显示对话框。
也可以(并且更容易)自己创建信号
在 .cpp 中(不要忘记包含 moc)
class FocusWatcher : public QObject
{
Q_OBJECT
public:
explicit FocusWatcher(QObject* parent = nullptr) : QObject(parent)
{
if (parent)
parent->installEventFilter(this);
}
virtual bool eventFilter(QObject *obj, QEvent *event) override
{
Q_UNUSED(obj)
if (event->type() == QEvent::FocusIn)
emit focusChanged(true);
else if (event->type() == QEvent::FocusOut)
emit focusChanged(false);
return false;
}
Q_SIGNALS:
void focusChanged(bool in);
};
并连接它:
connect(new FocusWatcher(myWidget), &FocusWatcher::focusChanged, this, &View::doSomething);