【问题标题】:QT QLineEdit focusoutQT QLineEdit 聚焦
【发布时间】:2017-01-24 07:45:45
【问题描述】:

我有一个带有掩码和 qvalidator(子类)的 QLineedit

如果输入与掩码或验证器不匹配,我如何防止移开焦点?

因为 mask 和 qvalidator 都不会阻止将焦点从 QLineEdit 移开。

并且编辑完成是行不通的,因为:

void QLineEdit::editingFinished()

当按下 Return 或 Enter 键或行编辑失去焦点时会发出此信号。请注意,如果在行编辑上设置了 validator() 或 inputMask() 并按下了 enter/return,则仅当输入遵循 inputMask() 并且 validator() 返回 QValidator 时才会发出 editingFinished() 信号: :可以接受。”

void MainWindow:n_lineEdit_editingFinished()
{
    if (ui->lineEdit->text() != "1111") ui->lineEdit->setFocus();
} 

所以掩码(验证器)不能与editingFinsihed 信号一起使用。

另外我已经试过了

bool MainWindow::eventFilter(QObject *filterObj, QEvent *event)
{
    if (filterObj == ui->lineEdit ) {
        if(event->type() == QEvent::FocusOut) {
            if (ui->lineEdit->text() != "1111") { ui->lineEdit-`>setFocus();};
        return true;
        };
    };
return false;
}

谢谢阿提拉

【问题讨论】:

    标签: qt


    【解决方案1】:

    来自 Qt 的文档:

    请注意,如果在行编辑中设置了验证器,则 returnPressed()/editingFinished() 信号只有在以下情况下才会发出 验证器返回QValidator::Acceptable

    但您可以将焦点放在每个事件上,而不仅仅是FocusOut

    bool MainWindow::eventFilter(QObject *filterObj, QEvent *event)
    {
        if (filterObj == ui->lineEdit ) 
            ui->lineEdit->setFocus();
    
        if(event->type() == QEvent::KeyRelease)
        {
            QKeyEvent* e = (QKeyEvent*)event;
    
            if(e->key() == Qt::Key_Return
                || e->key() == Qt::Key_Enter)
            {
                /* do what you want here */
            }
        }
    
        return QObject::eventFilter(filterObj, event); // usual process other events        
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-06
      • 2020-12-18
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多