Coverage for ibllib/misc/qt.py: 58%

19 statements  

« prev     ^ index     » next       coverage.py v7.5.4, created at 2024-07-08 17:16 +0100

1"""PyQt5 helper functions.""" 

2import logging 

3import sys 

4from functools import wraps 

5 

6from PyQt5 import QtWidgets 

7 

8_logger = logging.getLogger(__name__) 

9 

10 

11def get_main_window(): 

12 """Get the Main window of a QT application.""" 

13 app = QtWidgets.QApplication.instance() 

14 return [w for w in app.topLevelWidgets() if isinstance(w, QtWidgets.QMainWindow)][0] 

15 

16 

17def create_app(): 

18 """Create a Qt application.""" 

19 global QT_APP 

20 QT_APP = QtWidgets.QApplication.instance() 

21 if QT_APP is None: # pragma: no cover 

22 QT_APP = QtWidgets.QApplication(sys.argv) 

23 return QT_APP 

24 

25 

26def require_qt(func): 

27 """Function decorator to specify that a function requires a Qt application. 

28 

29 Use this decorator to specify that a function needs a running Qt application before it can run. 

30 An error is raised if that is not the case. 

31 """ 

32 @wraps(func) 

33 def wrapped(*args, **kwargs): 

34 if not QtWidgets.QApplication.instance(): 

35 _logger.warning('Creating a Qt application.') 

36 create_app() 

37 return func(*args, **kwargs) 

38 return wrapped 

39 

40 

41@require_qt 

42def run_app(): # pragma: no cover 

43 """Run the Qt application.""" 

44 global QT_APP 

45 return QT_APP.exit(QT_APP.exec_())