focus_persister.h 844 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. #pragma once
  8. namespace Ui {
  9. class FocusPersister {
  10. public:
  11. FocusPersister(QWidget *parent, QWidget *steal = nullptr)
  12. : _weak(GrabFocused(parent)) {
  13. if (steal) {
  14. steal->setFocus();
  15. }
  16. }
  17. ~FocusPersister() {
  18. if (auto strong = _weak.data()) {
  19. if (auto window = strong->window()) {
  20. if (window->focusWidget() != strong) {
  21. strong->setFocus();
  22. }
  23. }
  24. }
  25. }
  26. private:
  27. static QWidget *GrabFocused(QWidget *parent) {
  28. if (auto window = parent ? parent->window() : nullptr) {
  29. return window->focusWidget();
  30. }
  31. return nullptr;
  32. }
  33. QPointer<QWidget> _weak;
  34. };
  35. } // namespace Ui