当小部件失去焦点时的信号是什么? [英] What is the signal for when a widget loses focus?

查看:61
本文介绍了当小部件失去焦点时的信号是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在对话框中,当按下 tab 键时,焦点会更改为另一个小部件.在 Qt 中,当小部件失去焦点时是否有任何信号?我可以用它来检查输入是否有效吗?如果没有,我可以将焦点重新设置并要求用户重新输入吗?

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?

推荐答案

没有信号,但如果你想知道你的小部件何时失去焦点,覆盖并重新实现 void QWidget::focusOutEvent(QFocusEvent* event) 在您的小部件中.每当您的小部件失去焦点时,它就会被调用.要使小部件获得焦点,请使用 QWidget::setFocus(Qt::FocusReason).

There's no signal but if you want to know when your widget has lost focus, override and reimplement void QWidget::focusOutEvent(QFocusEvent* event) in your widget. It will be called whenever your widget has lost focus. To give focus to a widget, use QWidget::setFocus(Qt::FocusReason).

要验证 QLineEditQComboBox 中的输入,您可以子类化 QValidator 并实现您自己的验证器,或使用现有子类之一,QIntValidatorQDoubleValidatorQRegExpValidator.分别使用 QLineEdit::setValidator(const QValidator*)QComboBox::setValidator(const QValidator*) 设置验证器.

To validate input in a QLineEdit or QComboBox you can subclass QValidator and implement your own validator, or use one of the existing subclasses, QIntValidator, QDoubleValidator, or QRegExpValidator. Set the validator with QLine:setValidator(const QValidator*) and QComboBox::setValidator(const QValidator*) respectively.

如果您想验证模式对话框的内容,一种方法是使用如下实现覆盖 QDialog::exec():

If you want to validate the contents of a modal dialog box, one way would be to override QDialog::exec() with an implementation like this:

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 角色的按钮关闭对话框.在这个例子中,我假设对话框有一个名为 lineEditQLineEdit 并且 validate 函数将确保它的内容不为空.如果是,它会将焦点设置到 QLineEdit 并再次显示对话框.

It will not allow the user to close the dialog with the OK button or any other button with the Accepted role unless the contents of the dialog is successfully validated. In this example I assume the dialog has a QLineEdit named lineEdit and the validate function will make sure that its content is not empty. If it is, it will set the focus to the QLineEdit and show the dialog again.

这篇关于当小部件失去焦点时的信号是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆