qt_tab_key.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // This file is part of Desktop App Toolkit,
  2. // a set of libraries for developing nice desktop applications.
  3. //
  4. // For license and copyright information please follow this link:
  5. // https://github.com/desktop-app/legal/blob/master/LEGAL
  6. //
  7. #include "base/qt/qt_tab_key.h"
  8. #include "base/event_filter.h"
  9. #include <QApplication>
  10. #include <QKeyEvent>
  11. #include <QWidget>
  12. namespace base {
  13. bool FocusNextPrevChildBlocked(not_null<QWidget*> widget, bool next) {
  14. const auto skip = [&](QWidget *w) {
  15. return next ? w->nextInFocusChain() : w->previousInFocusChain();
  16. };
  17. const auto focused = QApplication::focusWidget();
  18. const auto start = focused ? focused : widget.get();
  19. auto w = skip(start);
  20. while (w && w != start) {
  21. if ((w->focusPolicy() & Qt::TabFocus) && widget->isAncestorOf(w)) {
  22. break;
  23. }
  24. w = skip(w);
  25. }
  26. if (w && w != start) {
  27. w->setFocus(next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
  28. }
  29. return true;
  30. }
  31. void DisableTabKey(QWidget *widget) {
  32. if (!widget) {
  33. return;
  34. }
  35. install_event_filter(widget, [=](not_null<QEvent*> e) {
  36. if (e->type() == QEvent::KeyPress) {
  37. const auto key = static_cast<QKeyEvent*>(e.get())->key();
  38. if ((key == Qt::Key_Tab) || (key == Qt::Key_Backtab)) {
  39. return base::EventFilterResult::Cancel;
  40. }
  41. }
  42. return base::EventFilterResult::Continue;
  43. });
  44. }
  45. } // namespace base