user1095108
user1095108

Reputation: 14603

prevent focus out for a QWidget

I'd like to write a QDialog lookalike class. I've managed to filter out mouse events to non-dialog widgets pretty well, but I still have a problem with focus. As the QDialog lookalike class is just a usual widget it can lose focus by way of key presses (tabs). Hence widgets not related to the QDialog lookalive, that I cannot click, but are focus-able, may get the focus. Is there a neat way to prevent the user from focusing away from my dialog lookalike's child widgets?

Upvotes: 4

Views: 7562

Answers (2)

user1095108
user1095108

Reputation: 14603

Here is a solution:

// somewhere in your code
connect(qApp, SIGNAL(focusChanged(QWidget*,QWidget*)),
  SLOT(focusChanged(QWidget*,QWidget*)));

void MyDialog::focusChanged(QWidget*, QWidget* to)
{
  if (!isAncestorOf(to))
  {
    QWidget* widget(qobject_cast<QWidget*>(children().front()));

    widget->setFocus(Qt::OtherFocusReason);

    QKeyEvent event(QEvent::KeyPress, Qt::Key_Tab, Qt::NoModifier);

    qApp->sendEvent(widget, &event);
  }
  // else do nothing
}

Assuming the child is an instance of QFrame or QWidget.

Upvotes: 4

Johannes S.
Johannes S.

Reputation: 4626

Assuming that your QDialog-like widget is an individual window, I think you are looking for QWdiget::setModal( true ). It prevents widgets in other windows of your application to receive any input events.

Upvotes: 5

Related Questions